Weird IllegalArgumentException in Calendar.getTime()

血红的双手。 提交于 2020-01-13 14:31:10

问题


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();
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/22351680/weird-illegalargumentexception-in-calendar-gettime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!