从TemporalAccessor获取OffsetDateTim

从TemporalAccessor获取OffsetDateTim

本文介绍了无法从TemporalAccessor获取OffsetDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时

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

我如何解析我的日期时间字符串,以便它被解释为始终来自时区欧洲/柏林?

How can I parse my datetime string so that it is interpreted as always being from the timezone "Europe/Berlin" ?

推荐答案

问题是 ZoneId ZoneOffset 之间存在差异。要创建 OffsetDateTime ,您需要一个区域偏移量。但因为它实际上取决于当前的夏令时。对于像欧洲/柏林这样的 ZoneId ,夏季有一个偏移,冬天有不同的偏移量。

The problem is that there is a difference between what a ZoneId is and a ZoneOffset is. To create a OffsetDateTime, you need an zone offset. But there is no one-to-one mapping between a ZoneId and a ZoneOffset because it actually depends on the current daylight saving time. For the same ZoneId like "Europe/Berlin", there is one offset for summer and a different offset for winter.

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

For this case, it would be easier to use a ZonedDateTime instead of an OffsetDateTime. During parsing, the ZonedDateTime will correctly be set to the "Europe/Berlin" zone id and the offset will also be set according to the daylight saving time in effect for the date to parse:

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 进入 OffsetDateTime

Note that if you really want an OffsetDateTime, you can use ZonedDateTime.toOffsetDateTime() to convert a ZonedDateTime into an OffsetDateTime.

这篇关于无法从TemporalAccessor获取OffsetDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:42