Calendar.getTime()失败,出现java.lang.IllegalArgumentException:MINUTE(亚洲/新加坡时区) [英] Calendar.getTime() fails with java.lang.IllegalArgumentException:MINUTE for Asia/Singapore timezone
问题描述
为什么此代码失败?目的是删除时间部分.
Why is this code failing? The purpose was to remove the time part.
String dateStr = "1982-01-01";
String timeZoneID = "Asia/Singapore";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone(timeZoneID));
calendar.setLenient(false);
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
System.out.println(calendar.getTime());
错误消息:
Exception in thread "main" java.lang.IllegalArgumentException: MINUTE
at java.util.GregorianCalendar.computeTime(GregorianCalendar.java:2482)
at java.util.Calendar.updateTime(Calendar.java:2265)
at java.util.Calendar.getTimeInMillis(Calendar.java:1049)
at java.util.Calendar.getTime(Calendar.java:1022)
at Prog.main(Prog.java:31)
在以下输入中工作正常:
It works fine for the following input:
- dateStr ="1982-01-01",timeZoneID =欧洲/柏林"
- dateStr ="1981-01-01",timeZoneID =亚洲/新加坡"
- dateStr ="1982-01-01",timeZoneID =亚洲/首尔"
推荐答案
您的代码从1982年1月1日开始,并将HOUR_OF_DAY和MINUTE都设置为0.
Your code starts with the date 1/1/1982 and sets both HOUR_OF_DAY and MINUTE to 0.
但是1982年1月1日,新加坡没有12:00:00 AM.1981年12月31日晚上11:59:59之后,新加坡跳了半个小时才到12:30 AM.它以前是UTC + 7:30,但移到了UTC + 8的全时区.
But there was no 12:00:00 AM on January 1, 1982, in Singapore. After 11:59:59 PM on December 31, 1981, Singapore jumped ahead by half an hour to 12:30 AM. It had previously been at UTC+7:30, but moved to the whole-hour zone of UTC+8.
来源:新加坡标准时间和 为什么新加坡处于错误"时区?/em> 简要了解新加坡的时间历史.
Sources: Singapore Standard Time and timeanddate.com. See also Why is Singapore in the "wrong" time zone? for a brief history of time in Singapore.
这篇关于Calendar.getTime()失败,出现java.lang.IllegalArgumentException:MINUTE(亚洲/新加坡时区)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!