简体   繁体   中英

how to convert Sting to ZonedDateTime in java

My input String do not have zone:

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);

My console print the 1st syso but after I have this error:

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)

Expected after plusDays(1) : 2019-12-18

A ZonedDateTime is an object aware of zone, date and time. You haven't provided any information about the time, so the String can just be parsed to an object aware of the date only.

However, you can use the beginning of a day in order to create a ZonedDateTime from a parsed LocalDate like this:

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);
}

which outputs

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

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