Search code examples
javajava-11datetime-parsinglocaldatetime

Local DateTime cannot be parsed in Java 11


I have below code.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
LocalDateTime myDate =  LocalDateTime.parse("2020-11-16T02:27:39.345Z", formatter);

But it throws below error in the second line. Not sure why it's complaining Z

java.time.format.DateTimeParseException: Text '2020-11-16T02:27:39.345Z' could not be parsed at index 23
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)

Solution

  • LocalDateTime does not have timezone or zone-offset information whereas your date-time string has zone-offset. The letter, Z at the end of your date-time string stands for Zulu i.e. zone-offset of UTC. You can parse it into OffsetDateTime or ZonedDateTime or Instant directly (i.e. without using a custom DateTimeFormatter).

    Demo:

    import java.time.Instant;
    import java.time.OffsetDateTime;
    import java.time.ZonedDateTime;
    
    public class Main {
        public static void main(String[] args) {
            String dateTimeString = "2020-11-16T02:27:39.345Z";
            OffsetDateTime odt = OffsetDateTime.parse(dateTimeString);
            System.out.println(odt);
            ZonedDateTime zdt = ZonedDateTime.parse(dateTimeString);
            System.out.println(zdt);
            Instant instant = Instant.parse(dateTimeString);
            System.out.println(instant);
        }
    }
    

    Output:

    2020-11-16T02:27:39.345Z
    2020-11-16T02:27:39.345Z
    2020-11-16T02:27:39.345Z