Format LocalDateTime with Timezone in Java8
The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime
). Despite the often misleading name such classes like LocalDateTime
or LocalTime
have NO timezone information or offset.
You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.
Solution:
Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime
(which contains an offset but not a timezone including DST-rules) or ZonedDateTime
. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds
is supported in OffsetDateTime
and ZonedDateTime
, but not in LocalDateTime
.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);
LocalDateTime
is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime
doesn't have such information. That's why the error occured.
If you want time-zone information, you should use ZonedDateTime
.
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"