java.time : DateTimeParseException for date “20150901023302166” [duplicate]

天涯浪子 提交于 2019-12-01 00:22:51

问题


LocalDateTime.parse("20150901023302166", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))

gives the error:

java.time.format.DateTimeParseException: Text '20150901023302166' could not be parsed at index 0


回答1:


A workaround is to build the formatter yourself using DateTimeFormatterBuilder and fixed width for each field. This code produces the correct result.

public static void main(String[] args) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .appendValue(ChronoField.YEAR, 4)
                                        .appendValue(ChronoField.MONTH_OF_YEAR, 2)
                                        .appendValue(ChronoField.DAY_OF_MONTH, 2)
                                        .appendValue(ChronoField.HOUR_OF_DAY, 2)
                                        .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
                                        .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
                                        .appendValue(ChronoField.MILLI_OF_SECOND, 3)
                                        .toFormatter();

    System.out.println(LocalDateTime.parse("20150901023302166", formatter));
}

So it looks like there is a problem with the formatter when building it from a pattern. After searching the OpenJDK JIRA, it seems this is indeed a bug, as referenced in JDK-8031085 and scheduled to be fixed in JDK 9.



来源:https://stackoverflow.com/questions/33896416/java-time-datetimeparseexception-for-date-20150901023302166

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!