Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

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();
like image 228
Allain Lalonde Avatar asked Sep 16 '08 13:09

Allain Lalonde


1 Answers

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));
like image 57
Argelbargel Avatar answered Oct 06 '22 20:10

Argelbargel