从 Instant 和 ZoneId 形成 ZonedDateTime 时的预期行为是什么?

What is the expected behavior when forming ZonedDateTime from Instant and ZoneId?

给定一个由时间戳(例如“2016-06-07 08-01-55”)和特定的 ZoneId ('Europe/Berlin') 组成的 Instant,此代码的预期结果是什么?

ZonedDateTime.ofInstant(timestamp.toInstant, zoneId)

会不会

'2016-06-07 08-01-55 +02:00' (time doesn't change, but ZoneId is changed)

'2016-06-07 10-01-55 +02:00' (time & ZoneId are changed)

我问这个问题是因为我在不同的环境中看到了这两种行为。

时刻总是从1970-01-01T00:00:00Z开始计算。因此,从瞬间创建 ZonedDateTime 会将瞬间时间戳转换为相应的区域。

在您的示例中,输入时间戳似乎不包含区域信息。最有可能的是,当它被解析为一个瞬间时,它会得到不同的结果,因为大多数解析器会假设时间戳在系统默认区域中。这可能会导致基于系统的不同瞬间,这是 运行,而这又会导致您观察到的不同行为。

假设您正确设置了每个参数,输出是确定性的。使用您的数据:

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]