ZonedDateTime.withZoneSameInstant 和 ZonedDateTime.withZoneSameLocal 有什么区别?

joh*_*ohn 12 java java-time

假设我有一个 ZonedDateTime:

ZonedDateTime zonedDateTime = 
     ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("US/Pacific"));
Run Code Online (Sandbox Code Playgroud)

我想知道它是在柏林的哪个日期/时间。我有两种方法:

zonedDateTime.withZoneSameInstant(ZoneId.of("Europe/Berlin")); // probably this is the right one to get the corresponding date/time in Berlin

zonedDateTime.withZoneSameLocal(ZoneId.of("Europe/Berlin"));
Run Code Online (Sandbox Code Playgroud)

withZoneSameLocal方法的文档说:“仅当本地日期时间对新区域无效时才会更改......”并且不清楚何时真的会发生(任何示例?=))。

它们各自代表哪个日期/时间,有什么区别?

shm*_*sel 18

如果要将时间戳从一个时区转换为另一个时区,请使用withZoneSameInstant(). withZoneSameLocal()将更改区域但保持所有其他字段相同。例外情况是该时区中的日期无效。

例如,

ZonedDateTime dtUTC = ZonedDateTime.parse("2019-03-10T02:30:00Z");
ZoneId pacific = ZoneId.of("US/Pacific");
System.out.println(dtUTC.withZoneSameInstant(pacific));
System.out.println(dtUTC.withZoneSameLocal(pacific));
Run Code Online (Sandbox Code Playgroud)

印刷

2019-03-09T18:30-08:00[US/Pacific]
2019-03-10T03:30-07:00[US/Pacific]
Run Code Online (Sandbox Code Playgroud)

第一行是转换为另一个时区的原始时间戳。第二个尝试保留日期/时间字段,但 2:30 不是该日期的有效时间(因为夏令时跳转),因此它将其移动了一个小时。