如果我们在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,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);
或者,由于在Temporal对象上工作的Duration. Between以及Instant和zoneddatetime都实现Temporal,您可以直接在zoneddatetime对象上调用Duration.between:
Duration duration = Duration.between(berlinDateTime,losDateTime2);
最后,还有一个如上所述的那个atao的快捷方式,如果你想要直接得到一个单位,比如总秒数,就可以了.任何这些都是可以接受的.