
您忘记设置时间了。
如果将我的答案与代码进行比较,您会注意到唯一的区别是时间信息丢失。一个
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}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)