【问题标题】:How to set the ZoneOffset for Berlin time zone如何设置柏林时区的 ZoneOffset
【发布时间】:2019-08-24 22:00:12
【问题描述】:
我得到的 LocalDateTime 比实际时间少两个小时。我如何获得德国的偏移时间,柏林时间为我的以下代码谢谢。
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
谢谢
【问题讨论】:
标签:
java
datetime
timezone
datetimeoffset
java-time
【解决方案1】:
使用ZoneId 和ZonedDateTime。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss", Locale.ENGLISH);
ZoneId zone = ZoneId.of("Europe/Berlin");
long seconds = 1_556_000_000;
ZonedDateTime dateTime = Instant.ofEpochSecond(seconds).atZone(zone);
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);
这个 sn-p 的输出是:
23.04.2019 08:13:20
我的示例秒值对应于 06:13:20 UTC,因此您已经得到了与 UTC 的两个小时偏移量。
夏令时 (DST) 是内置的,因此在冬季,您应该只获得 1 小时的 UTC 时间。抵消的历史性变化也是开箱即用的,以及已知的未来变化(没人知道 2021 年后德国会发生什么)。