【问题标题】:Checking if LocalDateTime falls within a time range检查 LocalDateTime 是否在时间范围内
【发布时间】:2018-04-07 03:06:38
【问题描述】:

我的时间 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;   
}

你能帮我看看这里的逻辑有什么问题吗?

【问题讨论】:

  • || 应该是&&

标签: datetime java-8 java-time localtime datetime-comparison


【解决方案1】:

LocalDateTime 实现了 Comparable 接口。为什么不使用它来检查一个值是否在这样的范围内:

public static boolean within(
    @NotNull LocalDateTime toCheck, 
    @NotNull LocalDateTime startInterval, 
    @NotNull LocalDateTime endInterval) 
{
    return toCheck.compareTo(startInterval) >= 0 && toCheck.compareTo(endInterval) <= 0;
}

【讨论】:

    【解决方案2】:

    作为@JB Nizet said in the comments,您使用的是 OR 运算符 (||)。
    所以你正在测试A is after B - 90 OR A is before B + 90。如果只满足其中一个条件,则返回true

    要检查A是否在范围内,必须同时满足两个条件,所以必须使用AND运算符(&amp;&amp;):

    if (timeA.isAfter(timeB.minusMinutes(90)) && timeA.isBefore(timeB.plusMinutes(90))) {
        return isInRange;   
    }
    

    但如果A正好B 之前或之后90 分钟,则上面的代码不会返回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 以分钟为单位获取AB 之间的差异,并检查其值:

    // get the difference in minutes
    long diff = Math.abs(ChronoUnit.MINUTES.between(timeA, timeB));
    if (diff <= 90) {
        return isInRange;
    }
    

    我使用了Math.abs,因为如果AB 之后,差异可能是负数(因此它被调整为正数)。然后我检查差异是否小于(或等于)90 分钟。如果要排除 “等于 90 分钟” 的情况,可以将其更改为 if (diff &lt; 90)


    这两种方法之间存在差异。

    ChronoUnit 舍入差值。例如如果AB 晚90 分59 秒,则差值将四舍五入到90 分钟,if (diff &lt;= 90) 将为true,而使用isBeforeequals 将返回false

    【讨论】:

      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多