Search code examples
javasimpledateformatdstdatetime-parsing

DST changes caused an java.text.ParseException: Unparseable date


Following is the code snippet which is throwing an exception:

SimpleDateformat dateFormatter = new SimpleDateFormat("yyyyMMddHHmm");
Date date = dateFormatter.parse("201710010200");

The code above threw exception for all the dates after 2:00 A.M. It ran well till 01:30 A.M.

DayLight saving time was configured (I'm using Australia/Sydney timezone).

After that, I could see logs of 3:00 A.M. Time between 2:00 A.M. and 3:00 A.M. is not logged too.

Log:

01 Oct 03:02:01 ERROR : Unparseable date: "201710010200"

Caused by: java.text.ParseException: Unparseable date: "201710010200" at java.text.DateFormat.parse(DateFormat.java:357)

What could be the fix of the problem of the date string "201710010200" not getting parsed, with the right date format specified?


Solution

  • You're trying to parse a date/time that didn't occur.

    We now know that this was in the Sydney time zone. At 2am on October 1st 2017 in Sydney, the clocks went forward to 3am. If you were looking at a clock every minute you'd see:

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

    So any date/time between 2am (inclusive) and 3am (exclusive) simply didn't occur in that time zone. We don't know what produced the values you're trying to parse, but:

    • If they're timestamps, it would almost certainly be better to both format and parse in UTC. Keep an offset from UTC and potentially a time zone ID if the time zone in which they were produced is important for future analysis.
    • If they're date/time values which aren't linked to any particular time zone, don't parse them as if they were in a time zone. Ideally, use Java 8's java.time package and parse them as LocalDateTime values