Duration. Between 与 ChronoUnit. Between

nim*_*o23 5 java java-time

这两种方法等效吗?

版本1:

var diff = Duration.between(begin, end).toHours();
Run Code Online (Sandbox Code Playgroud)

版本 2;

var diff = ChronoUnit.HOURS.between(begin, end);
Run Code Online (Sandbox Code Playgroud)

是否存在任何隐含的差异?如果是,我应该选择哪一个?

Pan*_*kos 3

分析开放 JDK 15 上的实现

A) Duration. Between(begin, end).toHours();

Duration.between(begin, end)第一次通话

long until(Temporal endExclusive, TemporalUnit unit); //called with unit of NANOS or SECONDS if first one fails
Run Code Online (Sandbox Code Playgroud)

然后解析差异以创建Duration基于已计算的纳秒(如果纳秒计算失败则创建秒)

public static Duration between(Temporal startInclusive, Temporal endExclusive) {
        try {
            return ofNanos(startInclusive.until(endExclusive, NANOS));
        } catch (DateTimeException | ArithmeticException ex) {
            long secs = startInclusive.until(endExclusive, SECONDS);
            long nanos;
            try {
                nanos = endExclusive.getLong(NANO_OF_SECOND) - startInclusive.getLong(NANO_OF_SECOND);
                if (secs > 0 && nanos < 0) {
                    secs++;
                } else if (secs < 0 && nanos > 0) {
                    secs--;
                }
            } catch (DateTimeException ex2) {
                nanos = 0;
            }
            return ofSeconds(secs, nanos);
        }
Run Code Online (Sandbox Code Playgroud)

然后你必须调用toHours()它,然后解析创建的Duration对象以返回小时数

B) ChronoUnit.HOURS. Between(开始,结束);

直接调用

long until(Temporal endExclusive, TemporalUnit unit);

//But instead of the implementation before, now it is called with unit of HOURS directly
Run Code Online (Sandbox Code Playgroud)

它直接返回小时数。

实现比较

两者的工作方式相同(至少几个小时)并给出相同的结果。

但对于A来说,我们似乎有一些不必要的来回转换。

解决方案B看起来很简单,没有任何我们不需要的转换

回答

我会选择B,因为效率更高