Unknown pattern letter: T - Parse string date with pattern T to LocalDateTime

Viewed 18467

I need to parse the following date format in String to Java LocalDateTime.

So I get date as String like this: 2019-09-20T12:36:39.359

I have the following unit test:

@Test
public void testDateTime() {
    assertEquals(SomeObject.getLocalDate(), LocalDateTime.parse(“2019-09-20T12:36:39.359”, DateTimeFormatter.ofPattern("yyyy-MM-ddThh:mm:ss.SSS")));
}

The unit test fails with exception:

java.lang.IllegalArgumentException: Unknown pattern letter: T

    at java.time.format.DateTimeFormatterBuilder.parsePattern(DateTimeFormatterBuilder.java:1661)
    at java.time.format.DateTimeFormatterBuilder.appendPattern(DateTimeFormatterBuilder.java:1570)
    at java.time.format.DateTimeFormatter.ofPattern(DateTimeFormatter.java:536)

How can I correctly parse the date in this format to LocalDateTime?

3 Answers

You can also use DateTimeFormatter.ofPattern as below

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault());

    String dateStr = "2019-09-20T12:36:39.359";

    LocalDateTime date = LocalDateTime.parse(dateStr, dtf);

You can use DateTimeFormatter.ISO_LOCAL_DATE_TIME as the formatter:

LocalDateTime.parse("2019-09-20T12:36:39.359", DateTimeFormatter.ISO_LOCAL_DATE_TIME);

You are comparing a String with a Date, that will say you they are not equals.

You don't even need to write the DateTimeFormatter.

Writing this code would be enough:

assertEquals("2019-09-20T12:36:39.359", LocalDateTime.parse("2019-09-20T12:36:39.359").toString());
Related