Search code examples
javadateparsingiso8601

SimpleDateFormat ISO having problems parsing the milliseconds if they have less than 3 digits


I'm trying to parse an String into a java.util.Date.

Currently, I'm using SimpleDateFormat, with the "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" format String, and it works pretty well most of the time; for example, those work okay:

  • "2022-03-16T12:09:56.267Z"
  • "2022-03-16T12:11:55.017+03:00"

The problem lies with perfectly valid ISO strings that happen to use less than three digits for the miliseconds:

  • "2022-03-16T09:18:31.9Z"

It throws this exception: java.text.ParseException: Unparseable date: "2022-03-16T09:18:31.9Z".

Is there a way to handle those? Please, do keep in mind that I need to return a java.util.Date, but using SimpleDateFormat is optional.

I'm using Java 8.


Solution

  • Here is one way.

    • Note the Z stands for Zulu.
    • And also remember that Date does not store any time zone information.
    • If necessary, you can modify the ZonedDateTime instance before converting to Date.
    Instant d = Instant.parse("2022-03-16T09:18:31.9Z");
    Date date = Date.from(d);
    System.out.println(d);
    System.out.println(date);
    

    prints

    2022-03-16T09:18:31.900Z
    Wed Mar 16 05:18:31 EDT 2022
    

    I would recommend that you try to convert to using the classes in the java.time package as they are quite superior to Date.