检查两个日期时段是否重叠
- 我有两个日期范围,(start1,end1)::: >> date1 &&(start2,end2)::: >> date2。
-
我想检查这两个日期是否已经过了。
-
我的流程图我假设“ =”运算符对比较有效 。
boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) { if (start1>=end2 && end2>=start2 && start2>=end2) { return false; } else { return true; } }
- 任何建议将不胜感激。
你可以使用Joda-Time 。
它提供了Interval
类,它指定了开始和结束时刻,并可以检查重叠的overlaps(Interval)
。
就像是
DateTime now = DateTime.now(); DateTime start1 = now; DateTime end1 = now.plusMinutes(1); DateTime start2 = now.plusSeconds(50); DateTime end2 = now.plusMinutes(2); Interval interval = new Interval( start1, end1 ); Interval interval2 = new Interval( start2, end2 ); System.out.println( interval.overlaps( interval2 ) );
版画
true
因为第一个间隔的结束落在第二个间隔的开始和结束之间。
boolean overlap(Date start1, Date end1, Date start2, Date end2){ return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime(); }
//the inserted interval date is start with fromDate1 and end with toDate1 //the date you want to compare with start with fromDate2 and end with toDate2 if ((int)(toDate1 - fromDate2).TotalDays < 0 ) { return true;} else { Response.Write(""); return false; } if ((int)(fromDate1 - toDate2).TotalDays > 0 ) { return true;} else { Response.Write(""); return false; }
你有两个间隔,i1和i2。 关于间隔如何在时间上相关的情况有六种情况(至少在牛顿世界观中),但只有两种是重要的:如果i1完全在i2之前,或者i1完全在i2之后; 否则两个间隔重叠(其他四个情况是i1包含i2,i2包含i1,i1包含i2的开头,i1包含i2的结尾)。 假设i1和i2的类型为Interval,其日期字段为beginTime和endTime。 那么函数是(注意,这里的假设是如果i1在i2结束的同时开始,反之亦然,我们不认为重叠并且我们认为给定的间隔endTime.before(beginTime)是假的) :
boolean isOverlapped(Interval i1, Interval i2) { return i1.endTime.before(i2.beginTime) || i1.beginTime.after(i2.endTime); }
在原始问题中,您指定DateTime而不是Date。 在java中,Date有日期和时间。 这与sql相反,其中Date在DateTime没有时间元素。 这是一个令人困惑的地方,当我第一次开始使用sql后,我已经偶然发现了多年。 无论如何,我希望这个解释是有帮助的。