【发布时间】:2018-12-27 02:49:55
【问题描述】:
我想在解析后将数组列表的元素转换为ZonedDateTime 对象。一个字符串如下所示。
"2017-02-12 06:59:00 +1300"
目前我使用DateTimeFormatter:
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss ZZ");
并尝试使用parse,获取时间:
this.actionTime = dateTimeFormatter.parse(actionTime, ZonedDateTime::from);
见下方法:
public DateCalculatorTest(String actionTime, int expectedDayOfWeek) {
DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss ZZ");
DateTimeFormatter localTimeFormatter =
DateTimeFormatter.ofPattern("YYYY-MM-dd");
this.actionTime = dateTimeFormatter.parse(actionTime, ZonedDateTime::from);
this.expectedDayOfWeek = expectedDayOfWeek;
}
但是,我无法解析字符串。我收到以下错误:
Text '2017-02-12 06:59:00 +1300' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {WeekBasedYear[WeekFields[SUNDAY,1]]=2017, DayOfMonth=12, MonthOfYear=2, OffsetSeconds=46800},ISO resolved to 06:59 of type java.time.format.Parsed
有没有办法用java.time 做到这一点?
【问题讨论】:
-
我将
YYYY(week-based-year) 更改为yyyy(year-of-era) 并使用System.out.println(ZonedDateTime.parse("2017-02-12 06:59:00 +1300", dateTimeFormatter));打印2017-02-12T06:59+13:00 -
您的字符串包含偏移量 (+1300),而不是时区(如 Pacific/Fakaofo),因此将其解析为
OffsetDateTime而不是ZonedDateTime.
标签: java time java-time datetime-parsing zoneddatetime