last day of month calculation
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.
And to get last day as Date object:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = cal.getTime();
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
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
.