How to get the last date of a particular month with JodaTime? How to get the last date of a particular month with JodaTime? java java

How to get the last date of a particular month with JodaTime?


How about:

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

dayOfMonth() returns a LocalDate.Property which represents the "day of month" field in a way which knows the originating LocalDate.

As it happens, the withMaximumValue() method is even documented to recommend it for this particular task:

This operation is useful for obtaining a LocalDate on the last day of the month, as month lengths vary.

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


Another simple method is this:

//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 correctlyanswer = answer.minusDays(1);


An old question, but a top google result when I was looking for this.

If someone needs the actual last day as an int instead using JodaTime you can do this:

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;}