tags:

views:

626

answers:

5

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();
+3  A: 

I would create a date object for the first day of the NEXT month, and then just subtract a single day from the date object.

Stephen Wrighton
This seems to be the common pattern to solve this problem in any language.
Kevin Ballard
some days are not 24 hours long, so this isn't an ideal solution. It'd work 95% of the time though.
Allain Lalonde
This is the more general-purpose language-indifferent solution.
clintp
+9  A: 
Argelbargel
+1  A: 

It looks like you set the calendar to the first day of the next month, so you need one more line to subtract one day, to get the last day of the month that sampleDay is in:

Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.roll(Calendar.MONTH, true);
cal.set(Calendar.DAY_OF_MONTH, 0);
cal.add(Calendar.DAY_OF_MONTH, -1);

In general, it's much easier to do this kind of thing using Joda Time, eg:

DateTime date = new DateTime(sampleDay.getTime());
return date.plusMonths(1).withDayOfMonth(0).minusDays(1).getMillis();
Peter Hilton
+1  A: 

Use calObject.getActualMaximum(calobject.DAY_OF_MONTH)

See Real's Java How-to for more info on this.

paul
A: 

I was wrong