首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java8中使用时区设置LocalDateTime格式

在Java8中使用时区设置LocalDateTime格式
EN

Stack Overflow用户
提问于 2014-08-29 11:42:56
回答 1查看 146.7K关注 0票数 147

我有这个简单的代码:

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

然后,我将得到以下异常:

java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds
at java.time.LocalDate.get0(LocalDate.java:680)
at java.time.LocalDate.getLong(LocalDate.java:659)
at java.time.LocalDateTime.getLong(LocalDateTime.java:720)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
at java.time.format.DateTimeFormatterBuilder$OffsetIdPrinterParser.format(DateTimeFormatterBuilder.java:3315)
at java.time.format.DateTimeFormatterBuilder$CompositePrinterParser.format(DateTimeFormatterBuilder.java:2182)
at java.time.format.DateTimeFormatter.formatTo(DateTimeFormatter.java:1745)
at java.time.format.DateTimeFormatter.format(DateTimeFormatter.java:1719)
at java.time.LocalDateTime.format(LocalDateTime.java:1746)

如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-29 12:07:13

LocalDateTime是不带时区的日期时间。您在格式中指定了时区偏移格式符号,但是LocalDateTime没有此信息。这就是错误发生的原因。

如果您需要时区信息,则应使用ZonedDateTime

DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"
票数 254
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25561377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档