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

Convert String into java.time.ZonedDateTime

我想在解析后将数组列表的元素转换为 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>>)));

我设法使用以下方法解决了这个问题:

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