[英]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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.