我有一个时间 A 应该在时间 B 的 90 分钟范围内(之前和之后)。
示例:如果 timeB 是 4:00 pm ,则时间 A 应该在 2:30pm (-90) 到 5:30pm (+90) 之间
尝试了以下方法:
if(timeA.isAfter(timeB.minusMinutes(90)) || timeA.isBefore(timeB.plusMinutes(90))) {
return isInRange;
}
你能帮我这里的逻辑有什么问题吗?
最佳答案
如 @JB Nizet said in the comments ,您正在使用 或 运算符 ( ||
)。
所以你正在测试是否 A is after B - 90
或 A is before B + 90
.如果仅满足其中一个条件,则返回 true
.
检查是否 A
在范围内,两个条件都必须满足,所以必须使用和 运算符( &&
):
if (timeA.isAfter(timeB.minusMinutes(90)) && timeA.isBefore(timeB.plusMinutes(90))) {
return isInRange;
}
但是上面的代码没有返回
true
如果 A
是 正好前后 90 分钟 B
.如果你想让它返回 true
当差异也恰好是 90 分钟时,您必须更改条件以检查:// lower and upper limits
LocalDateTime lower = timeB.minusMinutes(90);
LocalDateTime upper = timeB.plusMinutes(90);
// also test if A is exactly 90 minutes before or after B
if ((timeA.isAfter(lower) || timeA.equals(lower)) && (timeA.isBefore(upper) || timeA.equals(upper))) {
return isInRange;
}
另一种选择是使用
java.time.temporal.ChronoUnit
得到 A
之间的差异和 B
在几分钟内,并检查其值:// get the difference in minutes
long diff = Math.abs(ChronoUnit.MINUTES.between(timeA, timeB));
if (diff <= 90) {
return isInRange;
}
我用过
Math.abs
因为如果 A
差异可能是负数是在 B
之后(所以它被调整为一个正数)。然后我检查差异是否小于(或等于)到 90 分钟。您可以将其更改为 if (diff < 90)
如果要排除“等于 90 分钟”的情况。方法之间存在差异。
ChronoUnit
四舍五入的差异。例如如 A
是 B
之后的 90 分 59 秒,差异将四舍五入为 90 分钟和 if (diff <= 90)
将是 true
, 同时使用 isBefore
和 equals
将返回 false
.
关于datetime - 检查 LocalDateTime 是否在时间范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46942351/