【问题标题】:Convert String into java.time.ZonedDateTime将字符串转换为 java.time.ZonedDateTime
【发布时间】: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


【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-10
      • 2019-01-05
      • 2015-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-06
      相关资源
      最近更新 更多