首页 > 解决方案 > 无法使用特定格式将 String-Date 解析为 java.time.LocalDateTime

问题描述

以下代码使用带有时区偏移量的字符串中的日期打印输出。

String BERLIN_TIME_ZONE = "Europe/Berlin";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ssZ");
String dateTimeInString = formatter
        .format(ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(BERLIN_TIME_ZONE)));

System.out.println(dateTimeInString); // 2021-06-07T02:12:08+0200

这工作得很好。现在,此时我们有,所以我想通过使用方法dateTimeInString将它转换回对象。LocalDateTimeparse

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ssZ");
System.out.println(LocalDateTime.parse(dateTimeInString,formatter));

但是这种解析会引发异常。

Exception in thread "main" java.time.format.DateTimeParseException: Text '2021-06-07T02:12:08+0200' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {SecondOfMinute=8, MinuteOfHour=12, HourOfAmPm=2, OffsetSeconds=7200, NanoOfSecond=0, MilliOfSecond=0, MicroOfSecond=0},ISO resolved to 2021-06-07 of type java.time.format.Parsed
    at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at de.finhome.A.main(A.java:19)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {SecondOfMinute=8, MinuteOfHour=12, HourOfAmPm=2, OffsetSeconds=7200, NanoOfSecond=0, MilliOfSecond=0, MicroOfSecond=0},ISO resolved to 2021-06-07 of type java.time.format.Parsed
    at java.base/java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.base/java.time.format.Parsed.query(Parsed.java:235)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {SecondOfMinute=8, MinuteOfHour=12, HourOfAmPm=2, OffsetSeconds=7200, NanoOfSecond=0, MilliOfSecond=0, MicroOfSecond=0},ISO resolved to 2021-06-07 of type java.time.format.Parsed
    at java.base/java.time.LocalTime.from(LocalTime.java:431)
    at java.base/java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more

我检查了不同的资源,但无法找出问题所在。

标签: javajava-time

解决方案


将小时标记从 更改hhHH。小写h是 0-12,或者文档称为clock-hour-of-am-pm。大写H是 0-23,或者文档称为hour-of-day

虽然格式化程序可以在输出日期时非常高兴,但当您尝试读取相同的字符串时,它会产生歧义。解析器不知道...T01:...应该是凌晨 1 点还是下午。因为它不能明确地解析,所以它失败了。

或者,在 AM/PM 的格式字符串中添加一些内容(您可以使用a它)。然后解析器将能够明确地解释一个小时,例如 01。

似乎您也想更改LocalDateTime.parse为,ZonedDateTime.parse这样您就不会丢弃该区域。


推荐阅读