Calendar.getTime() fails with java.lang.IllegalArgumentException:MINUTE for Asia/Singapore timezone

眉间皱痕 提交于 2020-12-11 01:00:28

问题


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

The error message:

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 = "Europe/Berlin"
  • dateStr = "1981-01-01", timeZoneID = "Asia/Singapore"
  • dateStr = "1982-01-01", timeZoneID = "Asia/Seoul"

回答1:


Your code starts with the date 1/1/1982 and sets both HOUR_OF_DAY and MINUTE to 0.

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.

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.



来源:https://stackoverflow.com/questions/14968483/calendar-gettime-fails-with-java-lang-illegalargumentexceptionminute-for-asia

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