Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this date parsing fail? [duplicate]

I'm trying to convert a string into a LocalDateTime object.

@Test
public void testDateFormat() {
   String date = "20171205014657111";
   DateTimeFormatter formatter = 
       DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
   LocalDateTime dt = LocalDateTime.parse(date, formatter);
}

I would expect this test to pass.

I get the following error:

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

like image 583
user4184113 Avatar asked Dec 05 '17 02:12

user4184113


1 Answers

Looks like I may have run across this bug: https://bugs.openjdk.java.net/browse/JDK-8031085 as it corresponds to the JVM version I'm using. The workaround in the comments fixes the issue for me:

@Test
public void testDateFormat() {
    String date = "20171205014657111";
    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
       .appendPattern("yyyyMMddHHmmss")
       .appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter();
    LocalDateTime dt = LocalDateTime.parse(date, dtf);
}
like image 57
user4184113 Avatar answered Oct 06 '22 08:10

user4184113