英文:
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() <= fromB.getTime() && toB.getTime() <= 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 <= b1 || b2 <= a1
boolean overlapping = a2 > b1 && b2 > 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() >= fromB.getTime() && toB.getTime() >= 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论