I'm trying to write a DateTimeFormatter
to parse the following format:
2020-05-29T07:51:33.106-07:00
I have looked at ISO_OFFSET_DATE_TIME
, but the problem is it does not contain milliseconds. So I decided to write on my own.
It is easy to do so without timezone:
public static void main (String[] args) throws java.lang.Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(
LocalDateTime.parse("2020-05-29T07:51:33.106", formatter)
);
}
But when I tried to add a timezone in the format as
public static void main (String[] args) throws java.lang.Exception {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
System.out.println(
LocalDateTime.parse("2020-05-29T07:51:33.106-07:00", formatter)
);
}
It now fails with an exception that the timezone is unable to be parsed.
Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-05-29T07:51:33.106-07:00' could not be parsed at index 23
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1951)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at Ideone.main(Main.java:16)
How to parse a timezone in such a format?