2014-10-01 55 views
2

我正在使用joda.timeYearMonth對象,並且想要獲取此對象中月份日期的最後一天。如何在YearMonth對象中獲取月份的最後一天?

yearMonth.monthOfYear().getMaximumValue(); //return 12 as the maximum month value is =12 

但是我想要的是在特定月份的最大日期?大多數例如30或31。我怎麼才能得到它?

+0

重複http://stackoverflow.com/questions/13624442/getting-last-day-在給定的字符串日期的月份 – 2014-10-01 07:19:16

+0

可能的重複[如何獲取特定月份的最後日期與JodaTime?](http://stackoverflow.com/questions/9711454/how-to-get -Joadtime) – Jens 2014-10-01 07:19:55

+2

@Jayram他問的是使用jodatime而不是Calendar類。所以它不重複 – 2014-10-01 07:20:12

回答

9

的DateTime有這個現成的功能。

DateTime dt = new DateTime(); 
System.out.println(dt.dayOfMonth().getMaximumValue()); 

但是,如果你想爲YearMonth,然後再轉換到YearMonth DateTime和如上做:

YearMonth ym = new YearMonth(); 
dt = ym.toDateTime(null); 
System.out.println(dt.dayOfMonth().getMaximumValue()); 
0

如果你想在Joda月的最大一天,你應該使用LocalDate

如:

LocalDate endOfMonth = LocalDate.fromDateFields(new 
             Date()).dayOfMonth().withMaximumValue(); 
System.out.println(endOfMonth); 

輸出地說:

2014-10-31 

documentation

This operation is useful for obtaining a LocalDate on the last day of the month, 
as month lengths vary.  
LocalDate lastDayOfMonth = dt.dayOfMonth().withMaximumValue(); 
+0

正如上面所寫,我只*有'YearMonth'對象。我做*不*有'LocalDate' ... – membersound 2014-10-01 07:33:26

0

從yearMonth創建一個DateTime對象:

DateTime datetime = new DateTime(yearMonth.get(DateTimeFieldType.year()), yearMonth.get(DateTimeFieldType.monthOfYear()),1,0,0); 
System.out.println(datetime.dayOfMonth().getMaximumValue()); 
相關問題