两个时区之间的总飞行时间?

Total time of flight between two time zones?

如果我们在 14:05 离开法兰克福并在 16:40 到达洛杉矶。飞行时间是多少?

我尝试了以下方法:

ZoneId frank = ZoneId.of("Europe/Berlin");
ZoneId los = ZoneId.of("America/Los_Angeles");

LocalDateTime dateTime = LocalDateTime.of(2015, 02, 20, 14, 05);
LocalDateTime dateTime2 = LocalDateTime.of(2015, 02, 20, 16, 40);

ZonedDateTime berlinDateTime = ZonedDateTime.of(dateTime, frank);
ZonedDateTime losDateTime2 = ZonedDateTime.of(dateTime2, los);

int offsetInSeconds = berlinDateTime.getOffset().getTotalSeconds();
int offsetInSeconds2 = losDateTime2.getOffset().getTotalSeconds();

Duration duration = Duration.ofSeconds(offsetInSeconds - offsetInSeconds2);
System.out.println(duration);

但是我无法得到大约 11 小时 30 分钟的成功答案。请有人帮我解决上面的问题。谢谢你:)

getOffset是错误的方法。这会在该时间点获取该区域的 UTC 偏移量。它无助于确定一天中的实际时间。

一种方法是使用 toInstant 显式获取每个值表示的 Instant。然后使用Duration.between计算经过的时间。

Instant departingInstant = berlinDateTime.toInstant();
Instant arrivingInstant = losDateTime2.toInstant();
Duration duration = Duration.between(departingInstant, arrivingInstant);

或者,由于 Duration.between 适用于 Temporal 对象,并且 InstantZonedDateTime 都实现了 Temporal,您可以调用 Duration.between 直接在 ZonedDateTime 个对象上:

Duration duration = Duration.between(berlinDateTime, losDateTime2);

最后,如果您想直接使用诸如总秒数之类的度量单位,则可以使用像 atao 提到的快捷方式。这些都是可以接受的。

替换:

int offsetInSeconds = berlinDateTime.getOffset().getTotalSeconds();
int offsetInSeconds2 = losDateTime2.getOffset().getTotalSeconds();

Duration duration = Duration.ofSeconds(offsetInSeconds - offsetInSeconds2);

与:

long seconds = ChronoUnit.SECONDS.between(berlinDateTime, losDateTime2);
Duration duration = Duration.ofSeconds(seconds);

编辑

我喜欢 Matt Johnson 给出的最短(也是最短)的答案:

Duration duration = Duration.between(berlinDateTime, losDateTime2);