我想在解析后将数组列表的元素转换为 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
做到这一点?
最佳答案
在DateTimeFormatter
年应该是小写字母。替换
YYYY-MM-dd HH:mm:ss ZZ
与
yyyy-MM-dd HH:mm:ss ZZ
而且不需要两个ZZ,一个就够了。在您的代码中,ZoneId
实例将为您提供默认的 ZoneId
。它将返回到 LocalDateTime
。如果你想指定 ZoneId
使用下面的
this.actionTime = ZonedDateTime.parse(actionTime, dateTimeFormatter.withZone(ZoneId.of(<<yourxoneid>>)));
关于java - 将字符串转换为 java.time.ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51414625/