【问题标题】:What is the expected behavior when forming ZonedDateTime from Instant and ZoneId?从 Instant 和 ZoneId 形成 ZonedDateTime 时的预期行为是什么?
【发布时间】:2016-06-07 09:50:39
【问题描述】:
给定由时间戳(例如“2016-06-07 08-01-55”)和特定 ZoneId(“欧洲/柏林”)形成的 Instant,此代码的预期结果是什么?
ZonedDateTime.ofInstant(timestamp.toInstant, zoneId)
会不会
'2016-06-07 08-01-55 +02:00'(时间不变,但 ZoneId 变了)
或
'2016-06-07 10-01-55 +02:00'(时间和 ZoneId 已更改)
我问这个问题是因为我在不同的环境中看到了这两种行为。
【问题讨论】:
标签:
java
timezone
java-time
【解决方案1】:
假设您正确设置了每个参数,输出是确定性的。使用您的数据:
LocalDateTime datetime = LocalDateTime.of(2016, 6, 7, 8, 1, 55);
ZonedDateTime zdt = datetime.atZone(ZoneId.of("Europe/Berlin"));
Instant instant = zdt.toInstant();
Timestamp ts = Timestamp.from(instant); //The timestamp you describe in your question
ZonedDateTime result = ZonedDateTime.ofInstant(ts.toInstant(), ZoneId.of("Europe/Berlin"));
System.out.println(result); //WILL ALWAYS PRINTS: 2016-06-07T08:01:55+02:00[Europe/Berlin]
【解决方案2】:
时刻总是从 1970-01-01T00:00:00Z 开始计算。因此,从即时创建 ZonedDateTime 会将即时时间戳转换为相应的区域。
在您的示例中,输入时间戳似乎不包含区域信息。最有可能的是,当它被解析成一个瞬间时,它会产生不同的结果,因为大多数解析器会假设时间戳在系统默认区域中。这可能会导致基于运行此系统的不同时刻,而这反过来又会导致您观察到的不同行为。