Strange behaviour with GregorianCalendar

Posted by Spark on Stack Overflow See other posts from Stack Overflow or by Spark
Published on 2010-05-31T15:47:03Z Indexed on 2010/05/31 16:02 UTC
Read the original article Hit count: 328

Filed under:
|

I just encountered a strange behaviour with the GregorianCalendar class, and I was wondering if I really was doing something bad.

This only appends when the initialization date's month has an actualMaximum bigger than the month I'm going to set the calendar to.

Here is the example code :

    // today is 2010/05/31  
    GregorianCalendar cal = new GregorianCalendar();

    cal.set(Calendar.YEAR, 2010);
    cal.set(Calendar.MONTH, 1); // FEBRUARY

    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
    cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
    cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
    cal.set(Calendar.MILLISECOND, cal.getActualMaximum(Calendar.MILLISECOND));

    return cal.getTime(); // => 2010/03/03, wtf

I know the problem is caused by the fact that the calendar initialization date is a 31 day month ( may ), which mess with the month set to february (28 days). The fix is easy ( just set day_of_month to 1 before setting year and month ), but I was wondering is this really was the wanted behaviour. Any thoughts ?

© Stack Overflow or respective owner

Related posts about java

Related posts about j2ee