Format LocalDateTime with Timezone in Java8

后端 未结 3 753
时光说笑
时光说笑 2020-12-02 12:38

I have the this simple code:

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(\"yyyyMMdd HH:mm:ss.SSSSSS Z\");
LocalDateTime.now().format(FORMATTER)         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 13:16

    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);
    

提交回复
热议问题