Igor Wiwi
Igor Wiwi

Reputation: 43

SimpleDateFormat fails on particular date

On java 1.8 this code fails

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateFormat.setLenient(false);
dateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
dateFormat.parse("03/11/2007 02:05:01");

Interesting, that 03:05:01 parses correctly

Upvotes: 4

Views: 146

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500983

Yes, that's because 2007-03-11T02:05:01 never occurred in the America/New_York time zone.

The spring-forward daylight saving change occurred at 2007-03-11T07:00:00Z, so anyone watching a time-zone-aware clock would have seen:

  • 01:59:58
  • 01:59:59
  • 03:00:00
  • 03:00:01

You've told the SimpleDateFormat to handle the input strictly, then given it a date/time that didn't exist, so it's reasonable for it to fail.

Importantly, regardless of how you want to handle this, I would strongly encourage you to move off the legacy Date/Calendar/DateFormat types, and use java.time instead.

Upvotes: 13

Related Questions