有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一些text,只有在解析样式为Strict时才被DateTimeFormatter解析,而不是在Lenient

这似乎与我的预期相反

例如:

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

共 (1) 个答案

  1. # 1 楼答案

    将此作为bug发布后-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.

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