Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird IllegalArgumentException in Calendar.getTime()

Tags:

java

calendar

This perfectly simple test fails with IllegalArgumentException("HOUR_OF_DAY 2 -> 3"), and I see no reason why. You can change any of the hours, days, months, years to any other value and the test succeeds. Fails in any of the JRE's I tested on. Seems to be an internal problem in the GregorgianCalendar implementation? Or am I missing something obvious?

import java.util.Calendar;

public class DateTest extends TestCase
{
    /** test if 2011/03/27 02:30:00 converts to a valid date.
     * shouldn't throw any exception, however this throws 
     * IllegalArgumentException("HOUR_OF_DAY 2 -> 3)
     */
    @Test
    public void testDate()
    {
        Calendar cal = Calendar.getInstance();
        cal.setLenient(false);
        cal.clear();
        cal.set(Calendar.SECOND, 00);
        cal.set(Calendar.MINUTE, 30);
        cal.set(Calendar.HOUR_OF_DAY, 02);
        cal.set(Calendar.DAY_OF_MONTH, 27);
        cal.set(Calendar.MONTH, 03 - 1); // needs to be 0-based
        cal.set(Calendar.YEAR, 2011);
        cal.getTime();
    }
}
like image 724
geert3 Avatar asked Jan 12 '23 00:01

geert3


1 Answers

This date and time combination doesn't exist in your timezone, because it falls into discontinuity caused by daylight savings.

Since you configured setLenient(false), Calendar correctly throws an exception when you try to enter a non-existing date.

A rule of thumb: if you see something weird in date and time calculations, suspect daylight savings.

like image 51
axtavt Avatar answered Jan 19 '23 01:01

axtavt