栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解析日期时无法从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}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497885.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号