Search code examples
javascalaparsinglocaldatetime

Scala date parse with java LocalDateTime


I'm trying to parse a date like this "2020-07-01T00:00:00Z" with java LocalDateTime (in Scala) in this way:

LocalDateTime.parse("2020-07-01T00:00:00Z", ISO_INSTANT)

but I'm getting this exception:

java.time.format.DateTimeParseException: Text '2020-07-01T00:00:00Z' could not be parsed: Unable to obtain LocalDate from TemporalAccessor

What could be the problem here?

these are my libraries:

import java.time.format.DateTimeFormatter._
import java.time.LocalDateTime

Solution

  • You need to specify the zone the LocalDateTime is related to for parsing.

    LocalDateTime.parse("2020-07-01T00:00:00Z",
            DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()));
    

    A LocalDateTime stores no zone information but it is, abstractly speaking, related to one anyways. Multiple LocalDateTimes can be parsed from the same UTC timestamp, i.e. the time offset of the specific (local) zone is added/subtracted.

    Don't misunderstand this with ZonedDateTime. A ZonedDateTime stores zone information, thus it has a 1:1 relation to a UTC timestamp. A UTC timestamp has a 1:n relation to LocalDateTimes.