Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 663
Igor Wiwi Avatar asked Oct 26 '25 15:10

Igor Wiwi


1 Answers

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.

like image 151
Jon Skeet Avatar answered Oct 29 '25 03:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!