发布于 4年前

Java 8 时间解析的bug:java.time.format.DateTimeParseException: Text '20180225142051591' could not be parsed at index 0

Java 8的DateTimeFormatter在解析含有毫秒的时间字符串为LocalDateTime有bug,如下:

String x = "20180225142051591"; 
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"); 
LocalDateTime t1 = LocalDateTime.parse(x, dtf); 

抛出异常如下:

java.time.format.DateTimeParseException: Text '20180225142051591' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at java.time.LocalDateTime.parse(LocalDateTime.java:477)

这个是Java 8的一个bug:https://bugs.openjdk.java.net/browse/JDK-8031085

替代的解决方案

一个替代的解决方案是使用java.time.format.DateTimeFormatterBuilder结合java.time.temporal.ChronoField来处理毫秒或者纳秒。

String text = "20180225142051591";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // 解析date+time
    .appendPattern("yyyyMMddHHmmss")
    // 解析毫秒数
    .appendValue(ChronoField.MILLI_OF_SECOND, 3)
    .toFormatter();
formatter.parse(text);
©2020 edoou.com   京ICP备16001874号-3