无法从 TemporalAccessor 获取 OffsetDateTime

Unable to obtain OffsetDateTime from TemporalAccessor

当我这样做时

String datum = "20130419233512";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Europe/Berlin"));
OffsetDateTime datetime = OffsetDateTime.parse(datum, formatter);

我得到以下异常:

    java.time.format.DateTimeParseException: Text '20130419233512' could not be parsed: 
Unable to obtain OffsetDateTime from TemporalAccessor: {InstantSeconds=1366407312},ISO,Europe/Berlin resolved 
to 2013-04-19T23:35:12 of type java.time.format.Parsed

如何解析我的日期时间字符串,以便将其解释为始终来自时区 "Europe/Berlin"?

您的源数据中没有偏移量,因此 OffsetDateTime 不是解析期间使用的正确类型。

而是使用 LocalDateTime,因为这是与您拥有的数据最相似的类型。然后用atZone给它分配一个时区,如果你还需要一个OffsetDateTime,你可以从那里调用toOffsetDateTime

String datum = "20130419233512";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime datetime = LocalDateTime.parse(datum, formatter);
ZonedDateTime zoned = datetime.atZone(ZoneId.of("Europe/Berlin"));
OffsetDateTime result = zoned.toOffsetDateTime();

问题是 ZoneIdZoneOffset 是有区别的。要创建 OffsetDateTime,您需要一个区域偏移量。但是 因为它实际上取决于当前的夏令时。对于与 "Europe/Berlin" 相同的 ZoneId,夏季有一个偏移量,冬季有一个不同的偏移量。

对于这种情况,使用 ZonedDateTime 而不是 OffsetDateTime 会更容易。在解析期间,ZonedDateTime 将正确设置为 "Europe/Berlin" 区域 ID,偏移量也将根据要解析的日期生效的夏令时设置:

public static void main(String[] args) {
    String datum = "20130419233512";
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Europe/Berlin"));
    ZonedDateTime datetime = ZonedDateTime.parse(datum, formatter);

    System.out.println(datetime.getZone()); // prints "Europe/Berlin"
    System.out.println(datetime.getOffset()); // prints "+02:00" (for this time of year)
}

请注意,如果您确实想要 OffsetDateTime,可以使用 ZonedDateTime.toOffsetDateTime()ZonedDateTime 转换为 OffsetDateTime