如何使用 JodaTime 获取特定月份的最后一个日期?

我需要得到一个月的第一个日期(作为 org.joda.time.LocalDate)和最后一个。得到第一个是微不足道的,但是得到最后一个似乎需要一些逻辑,因为月份的长度不同,二月的长度甚至随着年份的不同而变化。JodaTime 中是否已经内置了相应的机制,或者我应该自己实现它?

61602 次浏览

这个怎么样:

LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();

dayOfMonth()返回一个 LocalDate.Property,它以知道原始 LocalDate的方式表示“每月的一天”字段。

碰巧,withMaximumValue()方法甚至是 记录在案,推荐它用于这个特定的任务:

此操作对于在月份的最后一天获取 LocalDate 非常有用,因为月份的长度不同。

LocalDate lastDayOfMonth = dt.dayOfMonth().withMaximumValue();

这是个老问题了,但是我在谷歌上找这个的时候得到的最好的搜索结果。

如果有人需要实际的最后一天作为一个 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;
}

Using JodaTime,we can do this :



public static final Integer CURRENT_YEAR = DateTime.now().getYear();


public static final Integer CURRENT_MONTH = DateTime.now().getMonthOfYear();


public static final Integer LAST_DAY_OF_CURRENT_MONTH = DateTime.now()
.dayOfMonth().getMaximumValue();


public static final Integer LAST_HOUR_OF_CURRENT_DAY = DateTime.now()
.hourOfDay().getMaximumValue();


public static final Integer LAST_MINUTE_OF_CURRENT_HOUR = DateTime.now().minuteOfHour().getMaximumValue();


public static final Integer LAST_SECOND_OF_CURRENT_MINUTE = DateTime.now().secondOfMinute().getMaximumValue();




public static DateTime getLastDateOfMonth() {
return new 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 类,其中包含许多有用的函数。

另一个简单的方法是:

//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);