Allain Lalonde Allain Lalonde - 5 months ago 10
Java Question

Given a Date Object how do I determine the last day of its month?

I'm trying to use the following code but it's returning the wrong day of month.

Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();

Answer

Get the number of days for this month:


Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

Set the Calendar to the last day of this month:


Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

Comments