java - 无法使用特定格式将 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
将它转换回对象。LocalDateTime
parse
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
我检查了不同的资源,但无法找出问题所在。
解决方案
将小时标记从 更改hh
为HH
。小写h
是 0-12,或者文档称为clock-hour-of-am-pm。大写H
是 0-23,或者文档称为hour-of-day。
虽然格式化程序可以在输出日期时非常高兴,但当您尝试读取相同的字符串时,它会产生歧义。解析器不知道...T01:...
应该是凌晨 1 点还是下午。因为它不能明确地解析,所以它失败了。
或者,在 AM/PM 的格式字符串中添加一些内容(您可以使用a
它)。然后解析器将能够明确地解释一个小时,例如 01。
似乎您也想更改LocalDateTime.parse
为,ZonedDateTime.parse
这样您就不会丢弃该区域。
推荐阅读
- javascript - 如何将值从服务传递到父组件
- json - 如何在特定条件下从 json 字典中删除整个元素(索引)
- python - 语法错误 || 不和谐.py || 第 18 行代码
- sorting - 根据特定字符串删除重复行
- batch-file - 通过 windows 命令行调用 gnome-session
- flutter - 无法使用 source_gen 为子包生成源
- reactjs - 如何设置 MenuItem 在里面
- html5-canvas - 使用画布调整图像尺寸并旋转 90 度
- python - 具有垂直边框和特定列颜色的 plotly 列
- arrays - 对于已在使用的控制变量编译错误