LocalDate正在默默地纠正不良日期?

end*_*ser 2 java java-date

我期望来自以下方面的例外:

LocalDate.parse("9/31/2018",DateTimeFormatter.ofPattern("M/d/yyyy"));
Run Code Online (Sandbox Code Playgroud)

但是相反,我得到了2018年9月30日!?别误会我的意思,它很聪明很不错,但是我已经期望Java的Date类的精度会更高……

谁能阐明为什么/为什么?这将弄乱我的测试。

Jon*_*eet 8

这是由于ResolverStyle格式化程序用于解析值。默认情况下(至少在我的机器上)它是“智能”的:

例如,使用智能模式在ISO日历系统中解析年月和月日将确保月日从1到31,将最后一个有效月日之后的任何值转换为最后一个有效日期。

...但是您可以改为“严格”,在这种情况下,解析将失败。完整示例(使用u而不是y避免不指定时代的歧义):

import java.time.*;
import java.time.format.*;

public class Test {

    public static void main (String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/uuuu");
        // With the "smart" resolver style, it parses
        System.out.println(formatter.getResolverStyle());
        LocalDate date = LocalDate.parse("9/31/2018", formatter);
        System.out.println(date);

        // But with a strict style...
        formatter = formatter.withResolverStyle(ResolverStyle.STRICT);
        LocalDate.parse("9/31/2018", formatter);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • “ Lenient”似乎解析为10/1/18。仅包括最后一个选项。 (2认同)