我有两个日期,格式如下 出生日期假设 1995/04/09 和当前日期 2016/07/24 那么我怎样才能获得到下一个生日的剩余月份和天数
public String getNextBirthdayMonths() {
LocalDate dateOfBirth = new LocalDate(startYear, startMonth, startDay);
LocalDate currentDate = new LocalDate();
Period period = new Period(dateOfBirth, currentDate);
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.appendMonths().appendSuffix(" Months ")
.appendDays().appendSuffix(" Days ")
.printZeroNever().toFormatter();
String nextBirthday = periodFormatter.print(period);
return "" + nextBirthday;
}
请任何人帮助我提前致谢
最佳答案
根据您的问题,您想使用 Joda 计算下一个生日。 下面的代码将帮助您给出即将到来的生日月份。
LocalDate dateOfBirth = new LocalDate(1995, 4, 9);
LocalDate currentDate = new LocalDate();
// Take birthDay and birthMonth from dateOfBirth
int birthDay = dateOfBirth.getDayOfMonth();
int birthMonth = dateOfBirth.getMonthOfYear();
// Current year's birthday
LocalDate currentYearBirthDay = new LocalDate().withDayOfMonth(birthDay)
.withMonthOfYear(birthMonth);
PeriodType monthDay = PeriodType.yearMonthDayTime().withYearsRemoved();
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.appendMonths().appendSuffix(" Months ").appendDays()
.appendSuffix(" Days ").printZeroNever().toFormatter();
if (currentYearBirthDay.isAfter(currentDate)) {
Period period = new Period(currentDate, currentYearBirthDay,monthDay );
String currentBirthday = periodFormatter.print(period);
System.out.println(currentBirthday );
} else {
LocalDate nextYearBirthDay =currentYearBirthDay.plusYears(1);
Period period = new Period(currentDate, nextYearBirthDay ,monthDay );
String nextBirthday = periodFormatter.print(period);
System.out.println(nextBirthday);
}
输出:
8 Months 16 Days
关于java - 如何使用 Joda 时间库计算下一个生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38552679/