1

I have String of time like: 2021-04-23T20:18:48.442826841Z How can I parse it to LocalDateTime? Which DateTimeFormatter I need to specify?

samabcde
  • 6,988
  • 2
  • 25
  • 41
DjFenomen
  • 87
  • 7
  • There is a pretty good documentation available here https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/time/format/DateTimeFormatter.html – aksappy Apr 26 '21 at 15:09
  • 1
    Did you try anything? – Eklavya Apr 26 '21 at 16:06
  • In which time zone do you want the resulting `LocalDateTime`? BTW don’t use `LocalDateTime` but `ZonedDateTime` for a date and time in a desired time zone. – Ole V.V. Apr 27 '21 at 12:06

2 Answers2

2

To begin, please read What's the difference between Instant and LocalDateTime?.

Referring to What exactly does the T and Z mean in timestamp?, the given string represent an Instant, and suppose you want a LocalDateTime with system default timezone, you may parse as following.

LocalDateTime.ofInstant(Instant.parse("2021-04-23T20:18:48.442826841Z"), ZoneId.systemDefault());

Or with DateTimeFormatter.ISO_INSTANT

LocalDateTime.parse("2021-04-23T20:18:48.442826841Z", DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()))
samabcde
  • 6,988
  • 2
  • 25
  • 41
0
LocalDateTime.parse("2021-04-23T20:18:48.442826841Z", DateTimeFormatter.ISO_LOCAL_DATE);

Works for me.

sproketboy
  • 8,967
  • 18
  • 65
  • 95
  • 1
    It gave me java.time.format.DateTimeParseException: Text '2021-04-23T20:18:48.442826841Z' could not be parsed, unparsed text found at index 10. – Ole V.V. Apr 27 '21 at 11:36