17

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?

M06H
  • 1,675
  • 3
  • 36
  • 76
  • 4
    you can escape the T with single quotes: "yyyy-MM-dd'T'hh:mm:ss.SSS" – Carlos Oct 01 '19 at 10:32
  • 1
    Your string is in [ISO 8601](https://en.wikipedia.org/wiki/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. – Ole V.V. Oct 01 '19 at 13:26

3 Answers3

21

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);
  • 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" )` – Basil Bourque Oct 01 '19 at 15:51
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);
Mushif Ali Nawaz
  • 3,707
  • 3
  • 18
  • 31
  • 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.000000359` – M06H Oct 01 '19 at 11:31
  • @M06H Here you are comparing two `String` values. You can easily strip the `0`s from the `String`. – Mushif Ali Nawaz Oct 01 '19 at 12:14
  • Ok and how about if it is localdatetime I compare instead of string? – M06H Oct 01 '19 at 12:44
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());
Paplusc
  • 1,080
  • 1
  • 12
  • 24