13

I am struggling with Java 8 DateTimeFormatter.

I would like to convert a given String to dateFormat and parse to LocalDateTime

Here is my code

DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")
String text = "2020-01-01T01:01:11.123Z"
LocalDateTime date = LocalDateTime.parse(text, f)

But Java throws

Text could not be parsed, unparsed text found at index 19

If I change ofPattern to yyyy-MM-dd'T'HH:mm:ss.SSSX, my code executes without any error. But I don’t want to use millisecond and time zone.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
J. Doem
  • 619
  • 7
  • 21

1 Answers1

12

Do this instead:

String text = "2020-01-01T01:01:11.123Z";
LocalDateTime date = ZonedDateTime.parse(text)
                                  .toLocalDateTime();

To get rid of the milliseconds information, do:

LocalDateTime date = ZonedDateTime.parse(text)
                                  .truncatedTo(ChronoUnit.SECONDS)
                                  .toLocalDateTime();

You can also use OffsetDateTime in place of ZonedDateTime.

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 3
    Good answer. I recommend `OffsetDateTime` since we have an offset ( `Z`) and no time zone (a time zone is a place on Earth and all the historic and known future changes to UTC offset in that place). – Ole V.V. Feb 16 '18 at 09:17