代码之家  ›  专栏  ›  技术社区  ›  Gili

Java11上的DateTimeParseException但适用于Java10

  •  4
  • Gili  · 技术社区  · 6 年前

    以下测试用例在Java 10下运行良好:

    import java.time.Instant;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeFormatterBuilder;
    
    class Test
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().
              appendPattern("EEE, dd MMM yyyy HH:mm:ss zzz").
              toFormatter();
            Instant result = dateFormatter.parse("Sat, 29 Sep 2018 20:49:02 GMT", Instant::from);
            System.out.println("Result: " + result);
        }
    }
    

    Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sat, 29 Sep 2018 20:49:02 GMT' could not be parsed at index 0
            at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
            at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
            at Test.main(Test.java:13)
    

    发生什么事?

    更新 toFormatter() 具有 toFormatter(Locale.US) 解决了问题。我猜这个问题与 https://bugs.openjdk.java.net/browse/JDK-8206980 . 这个问题在Java11Build23中被标记为已修复,但我正在运行

    openjdk version "11" 2018-09-25
    OpenJDK Runtime Environment 18.9 (build 11+28)
    OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
    

    这个版本不应该修正吗?

    更新2 :如果无法重现问题,请尝试替换 toFormatter() 具有 toFormatter(Locale.CANADA) .

    1 回复  |  直到 6 年前
        1
  •  8
  •   Basil Bourque    6 年前

    DateTimeFormatter.RFC_1123_DATE_TIME

    你的日期时间字符串在 RFC 822 / RFC 1123 DateTimeFormatter.RFC_1123_DATE_TIME :

        Instant result = DateTimeFormatter.RFC_1123_DATE_TIME
                .parse("Sat, 29 Sep 2018 20:49:02 GMT", Instant::from);
        System.out.println("Result: " + result);
    

    结果:2018-09-29T20:49:02Z

    按照RFC规范的要求,这个RFC1123格式化程序始终是英文的。我甚至试着把我的默认语言环境设置为 Locale.CANADA_FRENCH ,代码仍然有效。

    你的代码哪里出错了?

    Locale.CANADA : Sat. Sep. 而不是 Sat Sep . 在Java10中,它们应该没有点,所以这里的解析是有效的。区别可能在于CLDR数据的不同版本,在上述任何Java版本中都很难被视为bug。由于Java9CLDR是Java中的默认语言环境数据,包括不同语言环境中的日和月缩写。

    演示:使用格式化程序,但将其修改为

        DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().
                appendPattern("EEE, dd MMM yyyy HH:mm:ss zzz").
                toFormatter(Locale.CANADA);
        System.out.println("Sample: " + ZonedDateTime.now(ZoneId.of("America/Toronto"))
                .format(dateFormatter));
    

    在Java 10.0.2上运行时,这不会打印任何点:

    样本:太阳,2018年9月30日美国东部时间10:39:28

    在Java 11 build 11+28上:

    所以我相信这种行为与你链接的bug报告无关。

    链接