[英]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
对象, Instant
和ZonedDateTime
都可以实现Temporal
,因此您可以直接在ZonedDateTime
对象上调用Duration.between
:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.