Java 8 : Calculate difference between two ZonedDateTime

标签 java date datetime java-8 timezone

我正在尝试编写一个方法来打印两个 ZonedDateTime 之间的时差,关于时区之间的差异。

我找到了一些解决方案,但它们都是为使用 LocalDateTime 而编写的。

最佳答案

您可以使用 ChronoUnit 中的方法 between .

此方法将这些时间转换为相同的区域(来自第一个参数的区域),然后调用 Temporal 接口(interface)中声明的 until 方法:

static long zonedDateTimeDifference(ZonedDateTime d1, ZonedDateTime d2, ChronoUnit unit){
    return unit.between(d1, d2);
}

由于 ZonedDateTimeLocalDateTime 都实现了 Temporal 接口(interface),您还可以为这些日期时间类型编写通用方法:

static long dateTimeDifference(Temporal d1, Temporal d2, ChronoUnit unit){
    return unit.between(d1, d2);
}

但请记住,对 LocalDateTimeZonedDateTime 混合调用此方法会导致 DateTimeException

希望对您有所帮助。

关于Java 8 : Calculate difference between two ZonedDateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41077142/

相关文章:

日期时间格式转换为字符串忽略 AM/PM

java - 你如何防止 scanner.next() 包含换行符?

java - 使用内连接合并 2 个大型 csv 文件

javascript - SAPUI5后从日期选择器中选择后更改日期格式

python - 谷歌应用引擎数据存储日期时间到 Python 中的日期?

python - 读取以列名作为行的 csv 文件并编辑日期时间

java - java中的PubSub模型

java - 如何将 char 转换为对象

java - 将秒转换为 HH :MM:SS java 的问题

c# - 如何在 Visual Studio 中将当前时间转换为毫秒?