0

Trying to parse a ZonedDateTime from a date string e.g '2020-08-24'.

Upon using TemporalAccesor, and DateTimeFormatter.ISO_OFFSET_DATE to parse, I am getting a java.time.format.DateTimeParseException. Am I using the wrong formatter?

Even tried adding 'Z' at the end of date string for it to be understood as UTC

private ZonedDateTime getZonedDateTime(String dateString) {
  TemporalAccessor parsed = null;
  dateString = dateString + 'Z';
  try {
     parsed = DateTimeFormatter.ISO_OFFSET_DATE.parse(dateString);
  } catch (Exception e) {
     log.error("Unable to parse date {} using formatter DateTimeFormatter.ISO_INSTANT", dateString);
  }
  return ZonedDateTime.from(parsed);
}

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
USQ91
  • 342
  • 1
  • 4
  • 16
  • 7
    `yyyy-mm-dd` is pretty exactly the information stored in a `LocalDate`. To have a `ZoneDateTime` you need the time component and some zone information, which you don't seem to have. Why do you want to parse this to a `ZonedDateTime`? – Joachim Sauer Sep 24 '20 at 11:00
  • 3
    Indeed, even if you *eventually* want a ZonedDateTime, I think the expectations would be clearer if you parsed it as a LocalDate and then converted that to a ZonedDateTime by supplying a time-of-day and time zone. – Jon Skeet Sep 24 '20 at 11:07

3 Answers3

6

Use LocalDate#atStartOfDay

Do it as follows:

import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // Define a DateTimeFormatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd");

        // Given date string
        String strDate = "2020-08-24";

        // Parse the given date string to ZonedDateTime
        ZonedDateTime zdt = LocalDate.parse(strDate, dtf).atStartOfDay(ZoneOffset.UTC);

        System.out.println(zdt);
    }
}

Output:

2020-08-24T00:00Z
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

As mentionned in the post linked in comment section :

The problem is that ZonedDateTime needs all the date and time fields to be built (year, month, day, hour, minute, second, nanosecond), but the formatter ISO_OFFSET_DATE produces a string without the time part.

And the related solution

One alternative to parse it is to use a DateTimeFormatterBuilder and define default values for the time fields

IQbrod
  • 2,060
  • 1
  • 6
  • 28
0

offset in ISO_OFFSET_DATE means the timezone is specified as a relative offset against UTC

so something like "+01:00" is expected at the end of your input.

Paul Janssens
  • 622
  • 3
  • 9
  • 1
    `Z` is a correct offset in ISO-8601, You should check those documentations DateTimeFormatter https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_OFFSET_DATE and ZoneOffset https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html#getId-- – IQbrod Sep 24 '20 at 11:38