将字符串转换为java.time.ZonedDateTime

4
我希望将数组列表中的元素解析后转换为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的方法可以实现这个功能?

2
我将 YYYY(基于周的年份)更改为 yyyy(纪元年份),并使用 System.out.println(ZonedDateTime.parse("2017-02-12 06:59:00 +1300", dateTimeFormatter));,输出结果为 2017-02-12T06:59+13:00 - MadProgrammer
你的字符串包含一个偏移量(+1300),而不是时区(如太平洋/法考福),因此将其解析为OffsetDateTime而不是ZonedDateTime更正确,也更简单。 - Ole V.V.
2个回答

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

2
我使用以下方法成功解决了这个问题:
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss ZZ");
DateTimeFormatter localTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
this.symbol = symbol;
this.actionTime = ZonedDateTime.parse(actionTime, dateTimeFormatter);
this.actionDate = LocalDate.parse(expectedResult, localTimeFormatter);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接