无法从 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
如何解析我的日期时间字符串,以便将其解释为始终来自欧洲/柏林"时区?
How can I parse my datetime string so that it is interpreted as always being from the timezone "Europe/Berlin" ?
推荐答案
问题在于 ZoneId
和 ZoneOffset
之间存在差异.要创建 OffsetDateTime
,您需要一个区域偏移量.但是 ZoneId
和 ZoneOffset
之间没有一对一的映射 因为它实际上取决于当前的夏令时.对于相同的ZoneId
,如Europe/Berlin",夏季有一个偏移量,冬季有不同的偏移量.
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.toOffsetDateTime()
将 ZonedDateTime
转换为 OffsetDateTime
.
Note that if you really want an OffsetDateTime
, you can use ZonedDateTime.toOffsetDateTime()
to convert a ZonedDateTime
into an OffsetDateTime
.
这篇关于无法从 TemporalAccessor 获取 OffsetDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!