2014-10-01 154 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()); 
相关问题