Failed to get ZonedDateTime from TemporalAccessor when parsing date

With Java 1.8.0_51, the following code (taken from Failed to get OffsetDateTime from TemporalAccessor )

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneId.of("Europe/Berlin"));
OffsetDateTime offsetDateTime = ZonedDateTime.parse("20151113", formatter).toOffsetDateTime();
System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_DATE));

throws an exception:

java.time.format.DateTimeParseException: Text '20151113' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO,Europe/Berlin resolved to 2015-11-13 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1918)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1853)
at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)

What am I doing wrong this time?

+2
source share
2 answers

You forget to set the time.

If you compare my answer with the code, you may notice that the only difference is that the time information is missing. A ZonedDateTimecontains time information, and since your current formatter does not process it, an instance ZonedDateTimecannot be formed.

stacktrace,

Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO,Europe/Berlin resolved to 2015-11-13 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.ZonedDateTime.from(ZonedDateTime.java:560)
    ... 5 more

, , DateTimeFormatterBuilder parseDefaulting, . , NANO_OF_DAY 0.

public static void main(String[] args) {
    DateTimeFormatter formatter = 
        new DateTimeFormatterBuilder().appendPattern("yyyyMMdd")
                                      .parseDefaulting(ChronoField.NANO_OF_DAY, 0)
                                      .toFormatter()
                                      .withZone(ZoneId.of("Europe/Berlin"));

    OffsetDateTime offsetDateTime = ZonedDateTime.parse("20151113", formatter).toOffsetDateTime();
    System.out.println(offsetDateTime.format(DateTimeFormatter.ISO_DATE));
}

LocalDate, ZoneDateTime:

public static void main(String[] args) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    LocalDate parsed = LocalDate.parse("20151113", formatter);
    ZonedDateTime zonedDateTime = ZonedDateTime.of(parsed, LocalTime.MIDNIGHT, ZoneId.of("Europe/Berlin"));
    // get OffsetDateTime similarly
}
+4

Java 8 java.time.* - . - ZonedDateTime, , .

, , , , LocalDate.

+1

Source: https://habr.com/ru/post/1650509/


All Articles