检查LocalDateTime是否在一个时间范围内 [英] Checking if LocalDateTime falls within a time range

查看:9893
本文介绍了检查LocalDateTime是否在一个时间范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个时间A应该在90分钟的时间范围B(之前和之后)。

I have a time A which should fall within 90 minutes range of timeB (before and after).

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

Example: if timeB is 4:00 pm , time A should be between 2:30pm (-90) to 5:30pm (+90)

试过以下内容:

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

你能帮助我解决这里的逻辑错误吗?

Can you help me whats wrong with the logic here?

推荐答案

as @ JB Nizet在评论中说,您使用的是 OR 运算符( || )。$
所以你要测试的是 A是否在B-90之后 A在B + 90之前。如果只满足其中一个条件,则返回 true

As @JB Nizet said in the comments, you're using the OR operator (||).
So you're testing if A is after B - 90 OR A is before B + 90. If only one of the conditions is satisfied, it returns true.

检查 在此范围内,必须满足这两个条件,因此您必须使用 AND 运算符(&& ):

To check if A is in the range, both conditions must be satisfied, so you must use the AND operator (&&):

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






但上面的代码没有返回 true 如果 A 在<$ c $之前或之后90分钟完全 C> B 。如果您希望它返回 true ,当差异也是90分钟时,您必须更改条件以检查:


But the code above doesn't return true if A is exactly 90 minutes before or after B. If you want it to return true when the difference is also exactly 90 minutes, you must change the condition to check this:

// 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 以分钟为单位,并检查其价值:


Another alternative is to use a java.time.temporal.ChronoUnit to get the difference between A and B in minutes, and check its value:

// 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分钟的情况。

I used Math.abs because the difference can be negative if A is after B (so it's adjusted to be a positive number). Then I check if the difference is less than (or equal) to 90 minutes. You can change it to if (diff < 90) if you want to exclude the "equals to 90 minutes" case.

这些方法之间存在差异。

There's a difference between the approaches.

ChronoUnit 改变差异。例如如果 A B 之后90分59秒,则差异将四舍五入为90分钟且 if(diff< = 90) true ,同时使用 isBefore 等于将返回 false

ChronoUnit rounds the difference. e.g. If A is 90 minutes and 59 seconds after B, the difference will be rounded to 90 minutes and if (diff <= 90) will be true, while using isBefore and equals will return false.

这篇关于检查LocalDateTime是否在一个时间范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆