Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.time : DateTimeParseException for date "20150901023302166" [duplicate]

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

gives the error:

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

like image 352
thomas legrand Avatar asked Nov 24 '15 14:11

thomas legrand


1 Answers

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.

like image 154
Tunaki Avatar answered Nov 15 '22 17:11

Tunaki