【问题标题】:Unable to Convert Date and Time to LocalDateTime [Java]无法将日期和时间转换为 LocalDateTime [Java]
【发布时间】:2019-11-21 10:54:20
【问题描述】:

我正在尝试使用以下代码将字符串 Wed July 2019 10:53 PM 转换为 LocalDateTime 对象:

String dateAndTimeAsStr = "Wed July 2019 10:53 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMMM yyyy h:mm a");
LocalDateTime dateAndTimeAsLocalDateTime = LocalDateTime.parse(dateAndTimeAsStr, formatter);

然而,当我运行此代码时,我收到以下错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Wed July 2019 10:53 PM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfWeek=3, MonthOfYear=7, Year=2019},ISO resolved to 22:53 of type java.time.format.Parsed

yyyy 更改为YYYY 并将h 更改为hh 并没有产生任何不同的结果。

根据this answer on SOthe documentation 看来我的模式与提供的文本匹配。

我做错了什么?

谢谢

【问题讨论】:

  • 您期望哪个LocalDateTime 作为解析结果?

标签: java date datetime pattern-matching localdate


【解决方案1】:

缺少日期

您的输入字符串缺少月份中的日期。它说的是“2019 年 7 月”,但不是 7 月内的

格式化的日期字符串是不可逆的(因为您可以使用格式化程序格式化现有的 LocalDateTime,但不能将其解析回来)。因为它缺少日期值。

【讨论】:

  • 我试过了,它对我有用。或者您可以使用下面答案中建议的“日期”对象,这更宽容。
猜你喜欢
  • 2016-07-17
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 2019-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
相关资源
最近更新 更多