2012-03-14 69 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

相關問題