org.threeten.bp.format.DateTimeParseException

1.2k views Asked by At
val dateFormatter= DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd")
        .toFormatter()  

val begin = (LocalDateTime.parse("2019-11-04", dateFormatter).atOffset(ZoneOffset.UTC)
                    .toInstant()).atZone(ZoneId.of(timeZoneIdentifier))

When I try to parse the date like this, i get the following error:

Text '2019-11-04' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: DateTimeBuilder[, ISO, null, 2019-11-04, null], type org.threeten.bp.format.DateTimeBuilder

2

There are 2 answers

0
Anonymous On

Since 2019-11-04 is ISO 8601 format and LocalDate and the other java.time classes parse ISO 8601 format as their default, you don’t need any explicit formatter. Just this:

    val begin = LocalDate.parse("2019-11-04")
            .atStartOfDay(ZoneOffset.UTC)
            .withZoneSameInstant(ZoneId.of(timeZoneIdentifier))

Assuming that timeZoneIdentifier is Europe/Bucharest the result is a ZonedDateTime of 2019-11-04T02:00+02:00[Europe/Bucharest].

You cannot parse your string into a LocalDateTime. That would require not only a date but also a time of day, and as you know, your string contains only the former.

Link: Wikipedia article: ISO 8601

1
Matheus Lima On

use LocalDate instead LocalDateTime, Like this:

val begin = (LocalDate.parse("2019-11-04", dateFormatter).atOffset(ZoneOffset.UTC)
                .toInstant()).atZone(ZoneId.of(timeZoneIdentifier))

But this call require min api 26. For olders APIs, see here