解析日期时无法从TemporalAccessor获取ZonedDateTime

解析日期时无法从TemporalAccessor获取ZonedDateTime,第1张

解析日期时无法从TemporalAccessor获取ZonedDateTime

您忘记设置时间了。

如果将我的答案与代码进行比较,您会注意到唯一的区别是时间信息丢失。一个

ZonedDateTime
包含时间信息,并从当前的格式不处理它,实例
ZonedDateTime
不能形成即可。

您还可以在包含以下内容的stacktrace中看到它

Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO,Europe/Berlin resolved to 2015-11-13 of type java.time.format.Parsed    at java.time.LocalTime.from(LocalTime.java:409)    at java.time.ZonedDateTime.from(ZonedDateTime.java:560)    ... 5 more

根据您的需要,您可以使用构建一个自定义格式化程序,

DateTimeFormatterBuilder
并调用
parseDefaulting
来为每个时间计时字段提供默认值。如果要默认为午夜,则可以设置
NANO_OF_DAY
为0。

public static void main(String[] args) {    DateTimeFormatter formatter =         new DateTimeFormatterBuilder().appendPattern("yyyyMMdd")     .parseDefaulting(ChronoField.NANO_OF_DAY, 0)     .toFormatter()     .withZone(ZoneId.of("Europe/Berlin"));    OffsetDateTime offsetDateTime = ZonedDateTime.parse("20151113", formatter).toOffsetDateTime();    System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_DATE));}

另一个可能的解决方案是将文本解析为a

LocalDate
,然后
ZoneDateTime
使用它构造a :

public static void main(String[] args) {    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");    LocalDate parsed = LocalDate.parse("20151113", formatter);    ZonedDateTime zonedDateTime = ZonedDateTime.of(parsed, LocalTime.MIDNIGHT, ZoneId.of("Europe/Berlin"));    // get OffsetDateTime similarly}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5490006.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存