java – LocalDateTime format with Timezone in Java8

The prefix “Local” in JSR-310 (also known as Java.time-package in Java-8) does not indicate that there is a time zone information in the internal state of that class (here: LocalDateTime). Despite the often misleading name, classes like LocalDateTime or LocalTime they have no time zone or offset information.

You tried to format a time type (which does not contain any offset) with the offset information (indicated by the Z pattern symbol). Then the formatter attempts to access unavailable information and must throw the exception you observed.

Solution:

Use a type that has an offset or time zone data. In JSR-310 this is OffsetDateTime (which contains an offset but not a time zone that includes daylight saving time rules) or ZonedDateTime. You can check all supported fields of this type by consulting the method isSupported (TemporalField). . The field OffsetSeconds is supported in OffsetDateTime And ZonedDateTimebut not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

Leave a comment