问题
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);
}
回答1:
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
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/64044968/zoneddatetime-from-date-string-in-yyyy-mm-dd