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

gives the error:

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

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
thomas legrand
  • 493
  • 1
  • 5
  • 16

1 Answers1

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423