我正在尝试编写一个方法来打印两个 ZonedDateTime 之间的时差,关于时区之间的差异。
我找到了一些解决方案,但它们都是为使用 LocalDateTime 而编写的。
最佳答案
您可以使用 ChronoUnit 中的方法 between .
此方法将这些时间转换为相同的区域(来自第一个参数的区域),然后调用 Temporal 接口(interface)中声明的 until 方法:
static long zonedDateTimeDifference(ZonedDateTime d1, ZonedDateTime d2, ChronoUnit unit){
return unit.between(d1, d2);
}
由于 ZonedDateTime 和 LocalDateTime 都实现了 Temporal 接口(interface),您还可以为这些日期时间类型编写通用方法:
static long dateTimeDifference(Temporal d1, Temporal d2, ChronoUnit unit){
return unit.between(d1, d2);
}
但请记住,对 LocalDateTime 和 ZonedDateTime 混合调用此方法会导致 DateTimeException。
希望对您有所帮助。
关于Java 8 : Calculate difference between two ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077142/