比较时间

时间:2017-02-20 06:32:13

标签: java java-time

我无法理解,或者说无法证明:

(isAfter(x) or isEquals(x)) == !isBefore(x) 

(isBefore(x) or isEquals(x)) == !isAfter(x)

陈述总是如此

default boolean isAfter(ChronoZonedDateTime<?> other) {
        long thisEpochSec = toEpochSecond();
        long otherEpochSec = other.toEpochSecond();
        return thisEpochSec > otherEpochSec ||
            (thisEpochSec == otherEpochSec && toLocalTime().getNano() > other.toLocalTime().getNano());
    }

default boolean isBefore(ChronoZonedDateTime<?> other) {
        long thisEpochSec = toEpochSecond();
        long otherEpochSec = other.toEpochSecond();
        return thisEpochSec < otherEpochSec ||
            (thisEpochSec == otherEpochSec && toLocalTime().getNano() < other.toLocalTime().getNano());
    }

default boolean isEqual(ChronoZonedDateTime<?> other) {
        return toEpochSecond() == other.toEpochSecond() &&
                toLocalTime().getNano() == other.toLocalTime().getNano();
    }

来自java.time.chrono.ChronoZonedDateTime;

2 个答案:

答案 0 :(得分:1)

如果您的问题是,您是否可以证明isBeforeisEqualisAfter中只有一个是真的 - 是的,您可以。

this.toEpochSecond()other.toEpochSecond()之间有三种可能的比较:<==>。查看逻辑,很明显,如果比较为<,则isBefore()为真,isAfter()isEqual()为假,因为>和对==的{​​{1}}比较将是错误的。同样,如果比较为toEpochSecond,则>为真,isAfter()isBefore()为假。所以在这两种情况下,命题都成立了。

第三种情况怎么样,isEqual()结果相同?然后我们比较toEpochSecond,它可以是toLocalTime().getNano()<==。如果我们看一下当>结果相等且toEpochSecond结果进行比较时代码的行为,我们发现在所有三种情况下,其中一种方法返回true而其他方法返回false。

所以从本质上讲,我们已经研究了五种可能的情况,并且在所有情况下,这三种方法中只有一种是正确的。既然我们已经证明了这一点,那么原始问题中的陈述就是这样:

getNano

也是如此。 QED

答案 1 :(得分:0)

阅读条件,

(isBefore(x) or isEquals(x)) == !isAfter(x)

如果您是beforeequal,则不是after

示例:

如果您位于第二位或之后,则不能成为第一位。

如果两个条件都为真,则表示您是beforeequalafter。由于您不能afterbefore(除非您是一个盒子里的猫),您就是equal

代码说明

这些条件非常简单,首先它会尝试将第二秒的时间与toEpochSecond()进行比较。

然后,根据方法,它将检查纳秒值更精确。这部分将取决于方法。我们来一个:

default boolean isAfter(ChronoZonedDateTime<?> other) {
    long thisEpochSec = toEpochSecond();
    long otherEpochSec = other.toEpochSecond();
    return thisEpochSec > otherEpochSec ||
        (thisEpochSec == otherEpochSec && toLocalTime().getNano() > other.toLocalTime().getNano());
}

要检查this后是否other,我们需要检查this.seconds是否大于other.seconds

thisEpochSec > otherEpochSec 

如果没有,它将更深入并且仅在秒等于

时检查纳秒
thisEpochSec == otherEpochSec // seconds equals
    && toLocalTime().getNano() > other.toLocalTime().getNano());
相关问题