无法解析文本:无法从 TemporalAccessor 获取 LocalDateTime:

use*_*erx 1 time java-8

我编写了一段简单的代码来使用 java 8 api 解析日期。我还研究了有关此主题的各种其他堆栈溢出问题,但未能解决该错误。

package com.test.java8api;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, MM/DD/YYYY - HH:mm", Locale.ENGLISH).withResolverStyle(ResolverStyle.STRICT);
        LocalDateTime date = LocalDateTime.parse("Sun, 04/22/2018 - 09:45",formatter);
        System.out.println(date);
    }

}
Run Code Online (Sandbox Code Playgroud)

错误日志是

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sun, 04/22/2018 - 09:45' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfWeek=7, WeekBasedYear[WeekFields[SUNDAY,1]]=2018, MonthOfYear=4, DayOfYear=22},ISO resolved to 09:45 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at com.test.java8api.Test.main(Test.java:13)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfWeek=7, WeekBasedYear[WeekFields[SUNDAY,1]]=2018, MonthOfYear=4, DayOfYear=22},ISO resolved to 09:45 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {DayOfWeek=7, WeekBasedYear[WeekFields[SUNDAY,1]]=2018, MonthOfYear=4, DayOfYear=22},ISO resolved to 09:45 of type java.time.format.Parsed
    at java.time.LocalDate.from(LocalDate.java:368)
    at java.time.LocalDateTime.from(LocalDateTime.java:456)
    ... 4 more
Run Code Online (Sandbox Code Playgroud)

你能帮我解决这个问题吗?

编辑:

有人问我在解析 LocalDateTime (Java 8) 时是否可能重复无法从 TemporalAccessor 获取 LocalDateTime

情况并非如此,因为上述问题讨论了 LocalDate 和 LocalDateTime 的用法差异,而当前的问题是使用正确的符号或字母作为模式。

Bas*_*que 5

格式化模式区分大小写

“EEE,MM/DD/YYYY - HH:mm”

仔细阅读文档以了解格式化模式代码区分大小写。

  • DD表示一年中的某一天。dd表示月中的某一天。
  • YYYY表示基于周的年。yyyy(和uuuu) 表示日历年。

在发布到 Stack Overflow 之前请多加小心。您可以在 Stack Overflow 上找到数百个已发布的工作代码示例,以显示代码中的错误。


提示:避免自定义格式,例如在您的问题中看到的格式。将日期时间值序列化为文本时,请始终使用标准ISO 8601格式。它们非常实用和有用,旨在明确,易于机器解析,并且易于跨文化的人类阅读。

java.time类解析/生成的字符串时默认使用ISO 8601种格式。所以不需要指定格式模式。