165

I am having issues with the calculation of when the next Last Day of the Month is for a notification which is scheduled to be sent.

Here is my code:

RecurrenceFrequency recurrenceFrequency = notification.getRecurrenceFrequency();
Calendar nextNotifTime = Calendar.getInstance();

This is the line causing issues I believe:

nextNotifTime.add(recurrenceFrequency.getRecurrencePeriod(), 
                  recurrenceFrequency.getRecurrenceOffset());

How can I use the Calendar to properly set the last day of the next month for the notification?

2
  • 1
    Set it to the first day of the next month and then roll back one day. Feb 22, 2012 at 15:03
  • A SSCCE would make it easier to answer this question. What problem are you actually seeing?
    – DNA
    Feb 22, 2012 at 15:04

10 Answers 10

386
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);

This returns actual maximum for current month. For example it is February of leap year now, so it returns 29 as int.

6
  • thanks, I need to get the max for the next month however, also it still has to work that it can be the first day of the month as well, as that part works now. thanks again for your time and effort Feb 22, 2012 at 15:33
  • 5
    It is not a problem to get ActualMaximum for every date. Just roll calendar instance to required date before calling getActualMaximum. The first date can be obtained by getActualMinimum()
    – AlexR
    Feb 22, 2012 at 16:14
  • ok thanks so much Alex, so if I wish to roll the instance to a month ahead and find out the getActualMaximum for that month how would I do so?? cheers Feb 22, 2012 at 19:26
  • would this be it Alex? nextNotifTime.roll(Calendar.MONTH, true); nextNotifTime.getActualMaximum(Calendar.DAY_OF_MONTH); Feb 22, 2012 at 20:17
  • also I set the ready date time after this: nextNotification.setReadyDateTime(nextNotifTime.getTime()); therefore should I not do this instead: nextNotifTime.roll(Calendar.MONTH, true); nextNotifTime.getActualMaximum(Calendar.DAY_OF_MONTH); nextNotifTime.setTime(Calendar.DAY_OF_MONTH); ? Feb 22, 2012 at 20:22
75

java.time.temporal.TemporalAdjusters.lastDayOfMonth()

Using the java.time library built into Java 8, you can use the TemporalAdjuster interface. We find an implementation ready for use in the TemporalAdjusters utility class: lastDayOfMonth.

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

LocalDate now = LocalDate.now(); //2015-11-23
LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth()); //2015-11-30

If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

lastDay.atStartOfDay(); //2015-11-30T00:00
1
  • Good Answer. But that last part is weak, suggesting the use of LocalDateTime. That class lacks any concept of time zone or offset-from-UTC. So it cannot determine when a particular day in a particular place actually starts. That class only works for plain generic 24-hour days, not real-world days. For real days, specify a time zone: ZonedDateTime zdt = now.atStartOfDay( ZoneId.of( "Asia/Tokyo" ) ) ;. Some days in some places may start at a different time, such as 01:00, because of anomalies such as Daylight Saving Time (DST). Oct 2, 2019 at 21:11
40

And to get last day as Date object:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

Date lastDayOfMonth = cal.getTime();
0
22

You can set the calendar to the first of next month and then subtract a day.

Calendar nextNotifTime = Calendar.getInstance();
nextNotifTime.add(Calendar.MONTH, 1);
nextNotifTime.set(Calendar.DATE, 1);
nextNotifTime.add(Calendar.DATE, -1);

After running this code nextNotifTime will be set to the last day of the current month. Keep in mind if today is the last day of the month the net effect of this code is that the Calendar object remains unchanged.

0
20

Following will always give proper results:

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, ANY_MONTH);
    cal.set(Calendar.YEAR, ANY_YEAR);
    cal.set(Calendar.DAY_OF_MONTH, 1);// This is necessary to get proper results
    cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
    cal.getTime();
3
  • Why it's necessary? Could you tell me :)
    – Frank Fang
    Mar 28, 2015 at 13:02
  • 2
    Yep, just had tests fail for this exact reason above. The problem is that unless DAY_OF_MONTH is set, it will default to current.
    – ppearcy
    Mar 30, 2015 at 17:21
  • You should set (DAY_OF_MONTH, 1) first. If you are on 31th of January and set month to February it will skip to March, because the 31th of February does not exist. Calendar cal = DateUtils.getCalendar(2021, 1, 31); // DateUtils is custom. cal.set(Calendar.MONTH, Calendar.FEBRUARY); System.out.println(cal.getTime()); >>> Wed Mar 03 00:00:00 CET 2021 @mike Mar 26, 2021 at 9:20
10

Using the latest java.time library here is the best solution:

LocalDate date = LocalDate.now();
LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());

Alternatively, you can do:

LocalDate endOfMonth = date.withDayOfMonth(date.lengthOfMonth());
10

You can also use YearMonth.

Like:

YearMonth.of(2019,7).atEndOfMonth()
YearMonth.of(2019,7).atDay(1)

See https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#atEndOfMonth--

3

Look at the getActualMaximum(int field) method of the Calendar object.

If you set your Calendar object to be in the month for which you are seeking the last date, then getActualMaximum(Calendar.DAY_OF_MONTH) will give you the last day.

2
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date date = sdf.parse("11/02/2016");

        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(date);  

        System.out.println("First Day Of Month : " + calendar.getActualMinimum(Calendar.DAY_OF_MONTH));  
        System.out.println("Last Day of Month  : " + calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); 
2

Kotlin date extension implementation using java.util.Calendar

fun Date.toEndOfMonth(): Date {
    return Calendar.getInstance().apply {
        time = this@toEndOfMonth
    }.toEndOfMonth().time
}

fun Calendar.toEndOfMonth(): Calendar {
    set(Calendar.DAY_OF_MONTH, getActualMaximum(Calendar.DAY_OF_MONTH))
    return this
}

You can call toEndOfMonth function on each Date object like Date().toEndOfMonth()

2
  • 5
    These terrible classes were supplanted years ago by the modern java.time classes with the adoption of JSR 310. Suggesting these legacy classes in 2019 is poor advice. Mar 16, 2019 at 5:12
  • 1
    It is not a bad advice. The modern java.time is available for Android only for API 26+. We still depend on java.util.* when supporting (not so) old devices. May 6, 2020 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.