java. time:DateTimeParseException for date“20150901023302166”

See English answer > is Java time failing to parse fraction-of-second? two

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

给出错误:

java.time.format.DateTimeParseException: Text ‘20150901023302166’ Could not be parsed at index 0

Solution

The solution is to use datetimeformatterbuilder to automatically build formatter and fix the 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));
}@H_502_3@ 
 

所以看起来格式化程序在从模式构建时有问题.在搜索OpenJDK JIRA之后,似乎这是一个错误,正如JDK-8031085中所提到的,计划在JDK 9中修复.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>