【问题标题】:Unable to Convert Formatted String to LocalDateTime [duplicate]无法将格式化字符串转换为 LocalDateTime [重复]
【发布时间】:2019-09-12 03:55:10
【问题描述】:

我正在尝试使用以下代码将字符串 Fri August 16 2019 12:08:55 AM 转换为 LocalDateTime 对象:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMMM d YYYY h:mm:ss a", Locale.US);
String timestamp = "Fri August 16 2019 12:08:55 AM";
localDateTime = LocalDateTime.parse(timestamp, formatter);

此代码引发以下异常:

java.time.format.DateTimeParseException: Text 'Fri August 16 2019 12:08:55 AM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2019, MonthOfYear=8, DayOfWeek=5, DayOfMonth=16},ISO resolved to 00:08:55 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at suppliers.pojos.PriceFluctuationPOJO.<init>(PriceFluctuationPOJO.java:51)
    at suppliers.pojos.PriceFluctuationPOJO.readFromPriceFluctuationCSVFile(PriceFluctuationPOJO.java:163)
    at amzn.Main.main(Main.java:60)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2019, MonthOfYear=8, DayOfWeek=5, DayOfMonth=16},ISO resolved to 00:08:55 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(Unknown Source)
    at java.time.format.Parsed.query(Unknown Source)

基于 SO 上的 thisthis 线程,格式似乎是正确的。

是什么导致了异常?

谢谢

【问题讨论】:

  • 字符串内不用加单引号,去掉单引号

标签: java date datetime localdate


【解决方案1】:

您的输入 String 中不应包含单引号,并且您的模式已关闭。你想要yyyy(不是YYYY)。喜欢,

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMMM d yyyy hh:mm:ss a", Locale.US);
String timestamp = "Fri August 16 2019 12:08:55 AM";
LocalDateTime localDateTime = LocalDateTime.parse(timestamp, formatter);
System.out.println(localDateTime);

输出(此处)

2019-08-16T00:08:55

【讨论】:

  • 糟糕!我错误地复制了用于生成原始字符串 SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE MMMM YYYY h:mm:ss a"); 的模式但你是正确的 DateTimeFormatter 与 SimpleDateFormat 有不同的格式要求。谢谢!
  • @S.O.S SimpleDateFormat 出了名的麻烦和过时,你根本不应该使用它。无论如何,它在小写和大写 Y 之间具有相同的区别。对于格式化,98% 或 99% 的情况下结果将是相同的,因此您不太可能立即发现错误,但使用不正确的大小写仍然是一个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 2017-01-30
  • 2020-12-05
  • 2020-02-27
  • 1970-01-01
相关资源
最近更新 更多