且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java 8:计算两个ZonedDateTime之间的差异

更新时间:2022-03-06 01:09:03

ChronoUnit 之间的方法

此方法将这些时间转换为相同的区域(区域与第一个参数),之后,调用直到在 Temporal 界面中声明的方法: (d1,d2); $($)

You can use method between from ChronoUnit.
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);
}

既然 ZonedDateTime LocalDateTime 实现 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);
}

但请记住,调用此方法可以混合 LocalDateTime ZonedDateTime 导致 DateTimeException


希望它有帮助。

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

Hope it helps.