gpt4 book ai didi

java - 如何使用 Joda 时间库计算下一个生日

转载 作者:行者123 更新时间:2023-11-30 06:52:40 28 4
gpt4 key购买 nike

我有两个日期,格式如下出生日期假设为 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com