我的时间 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;
}
你能帮我这里的逻辑有什么问题吗?
我的时间 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 在评论中所说,您使用的是OR运算符 ( ||
)。
所以你正在测试 if A is after B - 90
OR A is before B + 90
。如果只满足其中一个条件,则返回true
。
要检查是否A
在范围内,必须同时满足两个条件,因此必须使用AND运算符 ( &&
):
if (timeA.isAfter(timeB.minusMinutes(90)) && timeA.isBefore(timeB.plusMinutes(90))) {
return isInRange;
}
true
但是,如果A
恰好是90 分钟 before 或 after ,则上面的代码不会返回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;
}
另一种选择是使用 a来获取和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
,差异可能是负数(所以它被调整为正数)。然后我检查差异是否小于(或等于)90 分钟。如果要排除“等于 90 分钟”的情况,可以将其更改为。A
B
if (diff < 90)
方法之间存在差异。
ChronoUnit
四舍五入的差异。例如如果A
是 90 分 59 秒之后B
,则差值将四舍五入到 90 分钟,并且会if (diff <= 90)
在true
使用时返回。isBefore
equals
false
LocalDateTime 实现了 Comparable 接口。为什么不使用它来检查一个值是否在这样的范围内:
public static boolean within(
@NotNull LocalDateTime toCheck,
@NotNull LocalDateTime startInterval,
@NotNull LocalDateTime endInterval)
{
return toCheck.compareTo(startInterval) >= 0 && toCheck.compareTo(endInterval) <= 0;
}