检查LocalDateTime是否在时间范围内

检查LocalDateTime是否在时间范围内,datetime,java-8,java-time,localtime,datetime-comparison,Datetime,Java 8,Java Time,Localtime,Datetime Comparison,我有一个时间a,它应该在时间B的90分钟范围内(之前和之后) 示例:如果时间B为下午4:00,则时间A应在下午2:30(-90)到下午5:30(+90)之间 尝试了以下操作: if(timeA.isAfter(timeB.minusMinutes(90)) || timeA.isBefore(timeB.plusMinutes(90))) { return isInRange; } 您能告诉我这里的逻辑有什么问题吗?因为您使用的是或运算符(|)。 因此,您正在测试A是在B-90之

我有一个时间a,它应该在时间B的90分钟范围内(之前和之后)

示例:如果时间B为下午4:00,则时间A应在下午2:30(-90)到下午5:30(+90)之间

尝试了以下操作:

if(timeA.isAfter(timeB.minusMinutes(90)) || timeA.isBefore(timeB.plusMinutes(90))) {
    return isInRange;   
}
您能告诉我这里的逻辑有什么问题吗?

因为您使用的是运算符(
|
)。
因此,您正在测试
A是在B-90之后还是在B+90之前。如果只满足其中一个条件,则返回
true

要检查
A
是否在范围内,必须同时满足这两个条件,因此必须使用运算符(
&&
):


但是,如果
A
B
之前或之后的90分钟
A
恰好时,上述代码不会返回
true
。如果您希望它在差值正好为90分钟时返回
true
,则必须更改条件以检查:

// 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;
}
//以分钟为单位计算差异
long diff=Math.abs(ChronoUnit.MINUTES.between(timeA,timeB));

if(diffLocalDateTime实现了可比较的接口。为什么不使用它来检查值是否在如下范围内:

public static boolean within(
    @NotNull LocalDateTime toCheck, 
    @NotNull LocalDateTime startInterval, 
    @NotNull LocalDateTime endInterval) 
{
    return toCheck.compareTo(startInterval) >= 0 && toCheck.compareTo(endInterval) <= 0;
}
内部的公共静态布尔值(
@NotNull LocalDateTime toCheck,
@NotNull LocalDateTime startInterval,
@NotNull LocalDateTime ENDPERVAL)
{

返回到check.compareTo(startInterval)>=0和&toCheck.compareTo(endInterval)
|
应该是
&&
public static boolean within(
    @NotNull LocalDateTime toCheck, 
    @NotNull LocalDateTime startInterval, 
    @NotNull LocalDateTime endInterval) 
{
    return toCheck.compareTo(startInterval) >= 0 && toCheck.compareTo(endInterval) <= 0;
}