Search code examples
javadatetimecalendar

How to calculate the last day of the month?


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?


Solution

  • 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.