[英]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.