Tuesday, August 30, 2011

Last Date Of Month - Java Implementation

A code snippet to set a Date object to the last date of the month:


Calendar cal = Calendar.getInstance();

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

System.out.println(cal.getTime());


The Calendar API has a lot of other utility methods that are very convenient when you need to work on dates.

1 comment:

Unknown said...

I've found issues with this because if you are including the time of the date then it's not necessarily the very "end" of the month. The time is set to whatever the Date instance you instantiated it with. So I've created helper methods that set the maximum hours/minutes/seconds for a date time. To me the true end of day is 24:59:59

/**
* @param date the date to find the month's ending day from. Cannot be null.
* @return the month's ending day. i.e. 12/15/2010 returns 12/31/2010 23:59:59.xxx
*/
public static Date lastDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
setMaximumValues(calendar);
return calendar.getTime();
}

/**
* Sets a date's HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND
* to the maximum value using calendar.getMaximum().
* @param calendar the date to set maximum time for
* @return the date with hours, minutes, seconds, and milliseconds set to the maximum time
*/
public static Date setMaximumTimeOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
setMaximumTimeOfDay(calendar);
return calendar.getTime();
}

/**
* Sets a calendar instances DAY_OF_MONTH, HOUR_OF_DAY, MINUTE, SECOND, and MILLISECOND
* to the maximum value using calendar.getMaximum().
* @param calendar the calendar instance to set minimum values
*/
public static void setMaximumValues(Calendar calendar) {
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setMaximumTimeOfDay(calendar);
}