Java 8:计算两个 ZonedDateTime 之间的差异 [英] Java 8: Calculate difference between two ZonedDateTime

查看:36
本文介绍了Java 8:计算两个 ZonedDateTime 之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write a method to print the time difference between two ZonedDateTimes, regarding the difference between time zones.

我找到了一些解决方案,但所有解决方案都是为使用 LocalDateTime 而编写的.

I found some solutions but all of them were written to work with LocalDateTime.

推荐答案

您可以使用来自 ChronoUnit.

You can use method between from ChronoUnit.

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

This method converts those times to same zone (zone from the first argument) and after that, invokes until method declared in Temporal interface:

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

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

Since both ZonedDateTime and LocalDateTime implements Temporal interface, you can write also universal method for those date-time types:

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

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

希望有帮助.

But keep in mind, that invoking this method for mixed LocalDateTime and ZonedDateTime leads to DateTimeException.

Hope it helps.

这篇关于Java 8:计算两个 ZonedDateTime 之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆