Calendar.getTime()中的怪异IllegalArgumentException [英] Weird IllegalArgumentException in Calendar.getTime()
问题描述
此完全简单的测试因 IllegalArgumentException( HOUR_OF_DAY 2-> 3)
而失败,我看不出原因。您可以将小时,天,月,年中的任何一个更改为任何其他值,然后测试成功。未能通过我测试的任何JRE。似乎是GregorgianCalendar实现中的内部问题?还是我遗漏了一些明显的东西?
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.
由于您配置了 setLenient(false)
,日历
在您尝试输入不存在的日期时正确地引发了异常
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.
这篇关于Calendar.getTime()中的怪异IllegalArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!