具有单个模式字母的 DateTimeFormatter 格式无法解析短月份名称

DateTimeFormatter format with a single pattern letter fails to parse short month name

当我 运行 下面列出的代码时,我看到以下错误:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'Thu Sep 21 23:47:03 EDT 2017' could not be parsed at index 4 at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source) at java.time.format.DateTimeFormatter.parse(Unknown Source) at java.time.LocalDate.parse(Unknown Source) at com.example.demo.DateTest.main(DateTest.java:16)

代码

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class DateTest {    
    public static void main(String[] args) {
        String date = "Thu Sep 21 23:47:03 EDT 2017";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E M d H:m:s z y", Locale.ENGLISH);
        LocalDate startDate = LocalDate.parse(date, formatter);
        System.out.println(date);           
    }    
}

您正在使用 M 作为月份格式说明符,但 M 是一个 number/text 字段,因此需要一个数值。

我还怀疑您指的是 HH:mm:ss 而不是时间部分的 H:m:s 和年份的 yyyy。 (后者不太可能成为问题,除非你确实有公元 1000 年之前的日期。)

这个有效:

DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("E MMM d HH:mm:ss z yyyy", Locale.ENGLISH);