Unknown pattern letter: T - Parse string date with pattern T to LocalDateTime [duplicate]
Asked Answered
G

3

20

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?

Genitourinary answered 1/10, 2019 at 10:25 Comment(2)
you can escape the T with single quotes: "yyyy-MM-dd'T'hh:mm:ss.SSS"Napiform
Your string is in ISO 8601 format, the default for LocalDateTime, so you can just leave out the formatter: LocalDateTime.parse("2019-09-20T12:36:39.359"). The parsed LocalDateTime object won’t ever be equal to a String, though.Pareu
R
25

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);
Reasoned answered 1/10, 2019 at 10:42 Comment(1)
No need to specify a formatting pattern. This input is in standard ISO 8601 format used by default when parsing/generating text. LocalDateTime.parse( "2019-09-20T12:36:39.359" )Flunkey
P
5

You can use DateTimeFormatter.ISO_LOCAL_DATE_TIME as the formatter:

LocalDateTime.parse("2019-09-20T12:36:39.359", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
Predominance answered 1/10, 2019 at 10:34 Comment(3)
How can we get the nanosecond to be exact and strip out the 0s java.lang.AssertionError: Expected :2019-09-20T12:36:39.359 Actual :2019-09-20T12:36:39.000000359Genitourinary
@Genitourinary Here you are comparing two String values. You can easily strip the 0s from the String.Predominance
Ok and how about if it is localdatetime I compare instead of string?Genitourinary
R
5

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());
Ranger answered 1/10, 2019 at 10:34 Comment(1)
The default DateTimeFormatter is DateTimeFormatter.ISO_LOCAL_DATE_TIME.Predominance

© 2022 - 2024 — McMap. All rights reserved.