我计算下一个生日剩余天数的代码在我使用闰年时给出了以下错误:当与2月29日一起使用时
** dayOfMonth的值29必须在1,28范围内
请帮我解决这个问题..。
public int getDaysRemainingForNextBirthDay(){
Calendar cal=Calendar.getInstance();
int currentYear=cal.get(Calendar.YEAR);
int currentMonth=cal.get(Calendar.MONTH);
int birthYear=currentYear;
int birthMonth=Integer.parseInt(m);
int birthDay=Integer.parseInt(d);
if (birthMonth<currentMonth) {
birthYear=birthYear+1;
}
DateTime birthDate=new DateTime(birthYear,birthMonth,birthDay,0, 0);
DateTime currentDate=DateTime.now();
Period datePeriod=new Period(currentDate,birthDate,PeriodType.days());
PeriodFormatter periodFormatter=new PeriodFormatterBuilder()
.appendDays().appendSuffix("").toFormatter();
return Integer.parseInt(periodFormatter.print(datePeriod));
}发布于 2015-03-25 20:15:00
问题是,在Java的Calendar中,月份是从0编号的,而在Joda Time中是从1编号的。
因此,在您的示例中,您将2作为月份传递,根据Calendar类,这是March,但是Joda时间框架将它解释为February。
要解决这个问题,只需将Calendar传递给Joda的月份加1即可。
https://stackoverflow.com/questions/20617429
复制相似问题