Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 736
M06H Avatar asked Oct 01 '19 10:10

M06H


People also ask

How do I parse LocalDateTime?

Parsing date and time To create a LocalDateTime object from a string you can use the static LocalDateTime. parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.

What is Z in LocalDateTime?

E.g: 2011-08-12T20:17:46.384Z. The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time. The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

How does LocalDateTime work?

LocalDateTime is an immutable date-time object that represents a date-time with default format as yyyy-MM-dd-HH-mm-ss. zzz. It provides a factory method that takes LocalDate and LocalTime input arguments to create LocalDateTime instance.


2 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);
like image 159
Sachini Wickramaratne Avatar answered Sep 21 '22 07:09

Sachini Wickramaratne


You can use DateTimeFormatter.ISO_LOCAL_DATE_TIME as the formatter:

LocalDateTime.parse("2019-09-20T12:36:39.359", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
like image 20
Mushif Ali Nawaz Avatar answered Sep 21 '22 07:09

Mushif Ali Nawaz