我需要获得一个月的第一个日期(作为org.joda.time.LocalDate
)和最后一个日期。获得第一个是微不足道的,但获得最后一个似乎需要一些逻辑,因为月份的长度不同,而2月的长度甚至随着时间的推移而变化。有没有一种机制已经内置到JodaTime中,或者我应该自己实现它?
发布于 2016-07-01 07:51:38
另一个简单的方法是:
//Set the Date in First of the next Month:
answer = new DateTime(year,month+1,1,0,0,0);
//Now take away one day and now you have the last day in the month correctly
answer = answer.minusDays(1);
发布于 2016-01-15 01:10:34
这是一个古老的问题,但在我寻找这篇文章时,谷歌的搜索结果却是排名靠前的。
如果有人需要实际的最后一天作为int
,而不是使用JodaTime,您可以这样做:
public static final int JANUARY = 1;
public static final int DECEMBER = 12;
public static final int FIRST_OF_THE_MONTH = 1;
public final int getLastDayOfMonth(final int month, final int year) {
int lastDay = 0;
if ((month >= JANUARY) && (month <= DECEMBER)) {
LocalDate aDate = new LocalDate(year, month, FIRST_OF_THE_MONTH);
lastDay = aDate.dayOfMonth().getMaximumValue();
}
return lastDay;
}
https://stackoverflow.com/questions/9711454
复制相似问题