2012-03-14 68 views
96

我需要得到一个月的最后一个日期(如org.joda.time.LocalDate)。获得第一个是微不足道的,但最后似乎需要一些逻辑,因为月份的长度不同,而且二月的长度甚至会在几年内变化。有没有一种机制已经内置于JodaTime中,还是我应该自己实现?如何使用JodaTime获取特定月份的最后日期?

+1

只是单挑,这也适用于'DateTime'类型:) – vikingsteve 2014-09-26 11:14:16

回答

186

如何:

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

dayOfMonth()返回LocalDate.Property代表现场“月日”在哪晓得始发LocalDate的方式。

当它发生时,withMaximumValue()方法甚至documented推荐它这个特殊的任务:

此操作是在每月的最后一天获得LOCALDATE的,因为一个月长度会有所变化非常有用。

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

@Jon Skeet如何使用Java 8的新日期和时间API来获取? – 2015-11-09 12:21:56

+4

@ WarrenM.Nocos:我会用'dt.with(TemporalAdjusters.lastDayOfMonth())' – 2015-11-09 12:38:20

0

一个老问题,但顶谷歌的结果时,我一直在寻找这一点。

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

使用JodaTime,我们可以这样做:

 

    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:A JodaTime and java.util.Date Util Class with a lot of usefull functions.

5

另一个简单的方法是这样的:

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

如果你的月份是12,那么会发生什么? – jon 2018-02-28 20:12:45

相关问题