Answers:
怎么样:
LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();
dayOfMonth()LocalDate.Property以知道来源的方式,返回代表“月中的月”字段的LocalDate。
碰巧的是,该withMaximumValue()方法甚至记录在案,以推荐用于此特定任务:
由于月份长度不同,此操作对于在每月的最后一天获取LocalDate很有用。
LocalDate lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
dt.with(TemporalAdjusters.lastDayOfMonth())
另一个简单的方法是:
//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);
一个老问题,但是当我寻找这个时,谷歌搜索结果最好。
如果有人需要实际的最后一天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;
}
使用JodaTime,我们可以这样做:
公共静态最终整数CURRENT_YEAR = DateTime.now()。getYear();
公共静态最终整数CURRENT_MONTH = DateTime.now()。getMonthOfYear();
公共静态最终整数LAST_DAY_OF_CURRENT_MONTH = DateTime.now()
.dayOfMonth()。getMaximumValue();
公共静态最终整数LAST_HOUR_OF_CURRENT_DAY = DateTime.now()
.hourOfDay()。getMaximumValue();
公共静态最终整数LAST_MINUTE_OF_CURRENT_HOUR = DateTime.now()。minuteOfHour()。getMaximumValue();
公共静态最终整数LAST_SECOND_OF_CURRENT_MINUTE = DateTime.now()。secondOfMinute()。getMaximumValue();
公共静态DateTime getLastDateOfMonth(){
返回新的DateTime(CURRENT_YEAR,CURRENT_MONTH,
LAST_DAY_OF_CURRENT_MONTH,LAST_HOUR_OF_CURRENT_DAY,
LAST_MINUTE_OF_CURRENT_HOUR,LAST_SECOND_OF_CURRENT_MINUTE);
}
如我在github上的要点所述: 具有许多有用功能的JodaTime和java.util.Date Util类。
DateTime类型:)