2

I'm using the YearMonth object of joda.time, and want to get the last day of the month date in this object.

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

But what I want is the maximum day in that specific month? Eg 30 or 31 mostly. How can I get it?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

3 Answers3

9

DateTime has this readymade feature.

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

But if you want it for YearMonth, then convert YearMonth to DateTime and do as above:

YearMonth ym = new YearMonth();
dt = ym.toDateTime(null);
System.out.println(dt.dayOfMonth().getMaximumValue());
faheem farhan
  • 401
  • 2
  • 9
0

If you want to get maximum day of the month in Joda you should use LocalDate

Eg:

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

Out put:

2014-10-31

From 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();
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

Create a DateTime Object from your yearMonth:

DateTime datetime = new DateTime(yearMonth.get(DateTimeFieldType.year()), yearMonth.get(DateTimeFieldType.monthOfYear()),1,0,0);
System.out.println(datetime.dayOfMonth().getMaximumValue());
Jens
  • 67,715
  • 15
  • 98
  • 113