如何在 java 中将 String 转换为 ZonedDateTime

how to convert Sting to ZonedDateTime in java

我的输入字符串没有区域:

String formatter = "yyyy-MM-dd";
String zone = "Europe/London";
String date = ZonedDateTime.now(ZoneId.of(zone)).format( DateTimeFormatter.ofPattern(formatter));
System.out.println("date: " + date);
// 
ZonedDateTime dateTime = ZonedDateTime.parse(date , DateTimeFormatter.ofPattern(formatter).withZone(ZoneId.systemDefault()));
String after = dateTime.plusDays(1).format( DateTimeFormatter.ofPattern(formatter));
System.out.println("after: " + after);

我的控制台打印第一个 syso,但出现此错误后:

date: 2019-12-17
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-12-17' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO,Europe/Paris resolved to 2019-12-17 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.ZonedDateTime.parse(ZonedDateTime.java:597)
    at com.id2s.application.business.service.impl.Sof.main(Sof.java:16)
Caused by: java.time.DateTimeException: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO,Europe/Paris resolved to 2019-12-17 of type java.time.format.Parsed
    at java.time.ZonedDateTime.from(ZonedDateTime.java:565)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

预计在 plusDays(1) 之后:2019-12-18

A ZonedDateTime 是一个可识别区域、日期 时间的对象。您还没有提供有关时间的任何信息,因此 String 只能解析为一个只知道日期的对象。

但是,您可以使用一天的开始从经过解析的 LocalDate 创建一个 ZonedDateTime,如下所示:

public static void main(String[] args) {
    String formatter = "yyyy-MM-dd";
    String zone = "Europe/London";
    String date = ZonedDateTime.now(ZoneId.of(zone))
            .format(DateTimeFormatter.ofPattern(formatter));
    System.out.println("date: " + date);
    // create a LocalDate first
    LocalDate localDate = LocalDate.parse(date);
    // then use that and the start of that day (00:00:00) in order to parse a ZonedDateTime
    ZonedDateTime dateTime = localDate.atStartOfDay(ZoneId.systemDefault()); 

    String after = dateTime.plusDays(1).format(DateTimeFormatter.ofPattern(formatter));
    System.out.println("after: " + after);
}

输出

date: 2019-12-17
after: 2019-12-18