DateTimeFormatter - 严格与宽松的意外行为

DateTimeFormatter - Strict vs Lenient unexpected behaviour

我有一些 text 仅在解析样式为 Strict 时由 DateTimeFormatter 解析 - 而不是在 Lenient.[=16= 时]

这似乎与我预期的相反?

示例:

String pattern = "ddMMyyHH:mm:ss";
String text = "02011104:21:32";

System.out.println(MessageFormat.format("Strict - {0}", new DateTimeFormatterBuilder().parseStrict().appendPattern(pattern).toFormatter().parse(text)));
System.out.println(MessageFormat.format("Lenient - {0}", new DateTimeFormatterBuilder().parseLenient().appendPattern(pattern).toFormatter().parse(text)));

输出:

Strict - {},ISO resolved to 2011-01-02T04:21:32
Exception in thread "main" java.time.format.DateTimeParseException: Text '02011104:21:32' could not be parsed at index 8

已将此作为错误发布 - https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8228353

我收到以下回复:

According to DateTimeFormatterBuilder's spec, appendPattern("yy") translates to appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2000), where "2" applies both for with and maxWidth. In the method description, it reads:

For strict parsing, the number of characters allowed by width to maxWidth are parsed. For lenient parsing, the number of characters must be at least 1 and less than 10.

因此在这种情况下,在严格模式下只为“yy”读取“11”,然后生成基值为 2000 的年份“2011”。但是在宽松模式下,“yy”会尝试贪婪地读取在“:”之前并生成年份“1104”,然后解析器抛出异常,试图用“HH”模式解析“:”。