2013-09-21 42 views
0
  • 我有两个日期范围(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; 
        } 
    } 
    
  • 任何建议将不胜感激。
+1

Java不支持重载操作符。 –

+0

这是正确的答案:http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap – BlueLettuce16

回答

10

您可以使用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 

由于第一间隔的末尾下降的开始和所述第二间隔的端部之间。

+0

感谢您的解决方法,但我们只是想使用该操作符。 并假定未排序的日期界限。 –

+1

@KhaledLela如果参数的顺序不正确,'Interval'类会抛出一个异常。你可以利用它来正确地实例化(或者使用日期的毫秒值来决定哪个先来)。 JodaTime解决方案比使用'>'和'<'提供更简洁的代码。 –

+0

要将此示例代码与现有java.util.Date对象一起使用,只需将每个Date实例传递给Joda-Time'DateTime'构造函数:'DateTime dateTimeStart1 = new DateTime(start1);' –

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

除了'start1'被声明为'Date'类型,其他的也是如此。 –

+0

哦,没有看到。现在更正。 –

+0

日期期间没有排序,比如“end1可能在start1之前”。 –

0
//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("<script>alert('there is an intersection between the inserted date interval and the one you want to compare with')</script>"); 
      return false; 
     } 

if ((int)(fromDate1 - toDate2).TotalDays > 0) 
     { return true;} 
else 
{  
Response.Write("<script>alert('there is an intersection between the inserted date interval and the one you want to compare with')</script>"); 
      return false; 
     } 
+0

你的代码是用Java以外的语言编写的吗?这个问题要求Java。在Java中,我们不能使用MINUS SIGN来减去一对Date实例。我不承认'.TotalDays'。 –

0

你有两个区间,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包含日期和时间。这与DateTime没有时间元素的sql相反。这是我在多年以来一直使用java之后第一次开始使用sql时偶然发现的一个混乱点。无论如何,我希望这个解释是有帮助的。

+0

这是不正确的。如果间隔'i1'完全在间隔'i2'之前,这仍然会返回true。 –