解析 Java 中一位数字的月份日期

Parsing day of month with one digit in Java

我想将字符串“OCTOBER81984”解析为 Java LocalDate。我正在使用以下代码但不起作用

LocalDate.parse("OCTOBER81984",
    new DateTimeFormatterBuilder() 
         .parseCaseInsensitive()
         .appendPattern("MMMMdyyyy")
         .toFormatter(Locale.US)
);

例外是

Exception in thread "main" java.time.format.DateTimeParseException: Text 'OCTOBER81984' could not be parsed at index 12
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)

使用的模式是

MMMM --> Full month name
d    --> Day of month with 1 or 2 digits
yyyy --> Year

我读了 the docs 两遍,我的模式看起来不错,但实际上行不通。

我错过了什么?

问题是您有 2 个可变宽度字段,日和年。解析器不够聪明,无法确定您的字符串并不意味着 984 年 10 月 81 日 (OCTOBER-81-984)。

在这个例子中,您可能认为知道 81st October 是胡言乱语可能足够聪明,但假设您的输入是 OCTOBER11984。很可能是 984 年 10 月 11 日。

如果您可以处理添加的年份必须为 4 位数字的约束,那么解析器就可以容忍月份中的第几天不是固定宽度这一事实。

试试这个:

LocalDate.parse("OCTOBER81984", 
    new DateTimeFormatterBuilder()
        .parseCaseInsensitive()
        .appendPattern("MMMM") // or .appendText(ChronoField.MONTH_OF_YEAR)
        .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER)
        .appendValue(ChronoField.YEAR_OF_ERA, 4)
        .toFormatter(Locale.US)
)