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

gives the error:

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

0

1 Answer 1

11

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.

2
  • Thanks for your help, i'll take that code until JDK9 Nov 24, 2015 at 15:01
  • 1
    Wow - I would never have expected the problem to be in constructing the formatter to start with. Nice catch :) Will remove my answer...
    – Jon Skeet
    Nov 25, 2015 at 7:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.