3

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

1 Answer 1

7

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.