Check if two date periods overlap [duplicate]

雨燕双飞 提交于 2019-11-28 00:36:20
Sotirios Delimanolis

You can use Joda-Time for this.

It provides the class Interval which specifies a start and end instants and can check for overlaps with overlaps(Interval).

Something like

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 ) );

prints

true

since the end of the first interval falls between the start and end of the second interval.

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("<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;
        }

You have two intervals, i1 and i2. There are six cases for how the intervals can be temporally related (at least in a Newtonian world view) but only two are important: if i1 is entirely before i2 or i1 is entirely after i2; otherwise the two intervals are overlapping (the other four cases are i1 contains i2, i2 contains i1, i1 contains the start of i2 and i1 contains the end of i2). Assume i1 and i2 are of type Interval that have Date fields beginTime and endTime. The function then is (note, the assumption here is that if i1 starts at the same time i2 ends, or vice versa, we don't consider that an overlap and we assme for a given interval endTime.before(beginTime) is false):

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

In the original question, you specify DateTime instead of Date. In java, Date has both date and time. This is in contrast to sql where Date does not have a time element while DateTime does. That is a point of confusion that I stumbled across when I first started using sql after having done only java for many years. Anyway, I hope this explanation is helpful.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!