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();
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With