我想要检查时间间隔

huangapple go评论77阅读模式
英文:

I want to check the time interval

问题

我想检查区间B是否在区间A内?
我的解决方案正确吗?

解决方案:

Date fromA;
Data toA;
Date fromB;
Date toB;
if(fromA.getTime() <= fromB.getTime() &&  toB.getTime() <= toA.getTime()){
// true
}
英文:

I want to check the interval B, whether it is in the interval A or not?
Is my solution correct?

solution:

Date fromA;
Data toA;
Date fromB;
Date toB;
if(fromA.getTime() &lt;= fromB.getTime() &amp;&amp;  toB.getTime() &lt;= toA.getTime()){
// true
}

答案1

得分: 3

Answer, 如果你是指 (非)重叠 的范围(而不是完全包含在另一个范围内):

最容易看出正确性的方法是排除范围,然后取反条件。

范围 (a1, a2) 和 (b1, b2):

boolean excluding = a2 <= b1 || b2 <= a1
boolean overlapping = a2 > b1 && b2 > a1    // 取反

因此,一个范围的交叉结束与另一个范围的开始相比。

你的代码可能是错误的。正确的写法是:

if (tomA.getTime() >= fromB.getTime() && toB.getTime() >= fromA.getTime()) {

由于 getTime() 返回一个 long 值,表示自 1970 年以来的毫秒数,因此在某个时候可能会出现有符号溢出。
这是非常理论性的问题,但并不是很好的情况。

更好的做法是使用新的 java.time API,它提供了更多的功能,并且可以使条件更易读。

英文:

Answer, should you mean (non-)overlapping ranges (instead of being fully contained inside an other range):

Easiest to see correctness is excluding ranges; and then negate the condition.

Ranges (a1, a2) and (b1, b2):

boolean excluding = a2 &lt;= b1 || b2 &lt;= a1
boolean overlapping = a2 &gt; b1 &amp;&amp; b2 &gt; a1    // Negation

So there is a cross-over end from one is compared to the start of the other.

You code must be wrong. Correct:

if (tomA.getTime() &gt;= fromB.getTime() &amp;&amp;  toB.getTime() &gt;= fromAgetTime()) {

As getTime() return a long, ms sind 1970, there might at one point be signed overflow.
Very theoretical, but not so nice.

Better would be to use the port of the new java.time API, which offer more functionality,
and would make the condition readable.

答案2

得分: 2

你的代码检查的是B是否在A中,而不是相反。

英文:

Your code checks if B is in A, not the other way round.

huangapple
  • 本文由 发表于 2020年10月14日 14:51:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64348022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定