本问题已经有最佳答案,请猛点这里访问。

我有两个日期范围,(start1,end1)::>>日期1&&(start2,end2):::>>日期2。

我想看看这两个日期是否重叠。

我的流程图假设"<>="运算符对于比较有效。

boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) {
if (start1>=end2 && end2>=start2 && start2>=end2) {
return false;
} else {
return true;
}
}

任何建议将不胜感激。

Java不支持重载运算符。

这是正确的答案:stackoverflow.com/questions/325933/&hellip;

你可以用Joda时间来做这个。

它提供了类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 ) );

印刷品2

因为第一个间隔的结束介于第二个间隔的开始和结束之间。

谢谢你的帮忙,但我们只想用那个接线员。并假定没有排序的日期界限。

@如果参数顺序不正确,Interval类的khaledlela将抛出异常。您可以利用它来正确地实例化(或者使用日期的毫秒值来决定哪一个在前面)。jodatime解决方案提供了比使用>和

要将此示例代码用于现有java.util.date对象,只需将每个日期实例传递给joda time DateTime构造函数:DateTime dateTimeStart1 = new DateTime( start1 );。

如果两个间隔相等,重叠将返回false!小心!

boolean overlap(Date start1, Date end1, Date start2, Date end2){
return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
}

除start1被宣布为Date型外,其他的也被宣布为Date型。

哦,没看见。更正了。

日期期间没有排序,比如"end1可能早于start1"。

那么你是说你的日期范围甚至可能无效?如果您还需要验证这一点,我将编写一个单独的方法。

你有两个间歇,I1和I2。关于间隔是如何与时间相关的有六种情况(至少在牛顿的世界观中),但只有两种情况是重要的:如果I1完全在I2之前,或者I1完全在I2之后;否则,这两种间隔是重叠的(其他四种情况是I1包含I2,I2包含I1,I1包含I2的开始,I1包含I2的结束)。。假定I1和I2属于具有日期字段BeginTime和EndTime的Interval类型。然后,函数是(注意,这里的假设是,如果I1在I2结束的同时开始,或者相反,我们不考虑重叠,我们假定给定的间隔结束时间。begintime之前(begintime)为false):

boolean isOverlapped(Interval i1, Interval i2) {
return i1.endTime.before(i2.beginTime) || i1.beginTime.after(i2.endTime);
}

在最初的问题中,您指定的是日期时间而不是日期。在Java中,日期既有日期又有时间。这与SQL相反,其中日期没有时间元素,而日期时间有时间元素。这是一个混乱点,当我第一次开始使用SQL之后,我做了很多年的Java。无论如何,我希望这个解释是有帮助的。

这是不正确的。如果区间i1完全在区间i2之前,则仍返回真值。

这真的是错的。正确的比较是:

!(beginPeriod1.isAfter(endPeriod2) || beginPeriod2.isAfter(endPeriod1))。
//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("alert('there is an intersection between the inserted date interval and the one you want to compare with')");
return false;
}
if ((int)(fromDate1 - toDate2).TotalDays > 0 )
{ return true;}
else
{
Response.Write("alert('there is an intersection between the inserted date interval and the one you want to compare with')");
return false;
}

你的代码是用Java以外的语言编写的吗?这个问题需要Java。在Java中,我们不能用减号来减去一对日期实例。我也不认识.TotalDays。