简体   繁体   中英

ZonedDateTime from date string in yyyy-mm-dd

Trying to parse a ZonedDateTime from a date string eg '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);
}

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM