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

查看:1576
本文介绍了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 之间的方法

此方法将这些时间转换为相同的区域(区域与第一个参数),之后,调用直到在 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.

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

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