LocalTime在23.59和00:01之间

isA*_*Don 15 java time localtime java-time

我想检查一下是否LocalTime是午夜.对于这种使用情况午夜被定义为任何之间23:5900:01.这是2分钟的范围.

private final LocalTime ONE_MINUTE_BEFORE_MIDNIGHT = LocalTime.of(23, 59, 0);
private final LocalTime ONE_MINUTE_AFTER_MIDNIGHT = LocalTime.of(0, 1, 0);
Run Code Online (Sandbox Code Playgroud)

我有一个方法

public boolean isAtMidnight(LocalTime time) {
    return time.isAfter(ONE_MINUTE_BEFORE_MIDNIGHT)
        && time.isBefore(ONE_MINUTE_AFTER_MIDNIGHT);
}
Run Code Online (Sandbox Code Playgroud)

此方法始终返回false.即使是LocalTime.MIDNIGHT.但它应该回归true.

如何查看+-1午夜时间是否分钟?

Jac*_* G. 17

取而代之的检查,如果time是之后23:59 之前00:01,你应该检查是否是后23:59 之前00:01.

public boolean isAtMidnight(LocalTime time){
    return time.isAfter(ONE_MINUTE_BEFORE_MIDNIGHT) || time.isBefore(ONE_MINUTE_AFTER_MIDNIGHT);
}
Run Code Online (Sandbox Code Playgroud)

如果我们查看实现LocalTime#isAfter,我们会看到以下内容:

public boolean isAfter(LocalTime other) {
    return compareTo(other) > 0;
}
Run Code Online (Sandbox Code Playgroud)

LocalTime#compareTo:

@Override
public int compareTo(LocalTime other) {
    int cmp = Integer.compare(hour, other.hour);
    if (cmp == 0) {
        cmp = Integer.compare(minute, other.minute);
        if (cmp == 0) {
            cmp = Integer.compare(second, other.second);
            if (cmp == 0) {
                cmp = Integer.compare(nano, other.nano);
            }
        }
    }
    return cmp;
}
Run Code Online (Sandbox Code Playgroud)

我们可以看到,两个实例LocalTime首先按它们各自的小时数进行比较,然后是分钟,然后是秒,最后是纳秒.对于LocalTime#compareTo返回大于值0满足LocalTime#isAfter,第一小时LocalTime实例必须大于第二实例的更大.这是不是真正的00:0023:59,因此为什么你的方法返回false.可以进行相同的分析LocalTime#isBefore,您将得到相同的结果.

请记住,LocalTime.MIDNIGHT如果你想要确切,你可以检查,但我认为你正在考虑在1分钟范围内的任何时间是"午夜"(包括秒).


Tam*_*Rev 16

解决方案是使用||而不是&&:

public boolean isAtMidnight(LocalTime time) {
    return time.isAfter(ONE_MINUTE_BEFORE_MIDNIGHT) || time.isBefore(ONE_MINUTE_AFTER_MIDNIGHT);
}
Run Code Online (Sandbox Code Playgroud)

这是违反直觉的,不是吗?诀窍是00:00:01不会追随23:59,所以总是会失败.这是因为LocalTime.isAfterLocalTime.isBefore假设那些是同一天的时间.

  • 这是一个比最高投票更好的答案. (3认同)