Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare intersection of two datetime interval in javascript

I have two date time interval :

first stardate : 2014-06-20#00:01
first enddate  : 2014-06-24#23:59

second startdate : 2014-06-25#00:01
second enddate   : 2014-06-27#23:59

I can compare startdate < enddate with parsing to int 201406200001 < 201406242359

But I want to compare intersection of first date interval and second date interval.

First interval can be > or < second interval but these two intervals should not have any intersection.

How can I write this algorithm in javascript ?

like image 959
pckmn Avatar asked Dec 21 '25 00:12

pckmn


2 Answers

Well, if you can compare them as numbers :

if( (start1 > start2 && start1 < end2) || (start2 > start1 && start2 < end1) ) 

This is true for overlapping intervals.

Basically, it checks if the start of the first interval is inside the second interval or if the start of the second one is inside the first one.

like image 123
PurkkaKoodari Avatar answered Dec 22 '25 15:12

PurkkaKoodari


This solved my problem, like this question proposes. I needed to grab this solution from another link. I just adapted it to dates, as the question proposes.

Testing is easy. You can use the browser's console.

function intercept(start1,end1,start2,end2) {
    return ( Math.max(0, Math.min(end2, end1) - Math.max(start1, start2) + 1) ) > 0
}

console.log('I should be true >> ', intercept(new Date("2018/01/01"), new Date("2018/01/05"), new Date("2018/01/05"), new Date("2018/02/03")))
console.log('I should be false >> ', intercept(new Date("2018/01/01"), new Date("2018/01/05"), new Date("2018/01/06"), new Date("2018/02/03")))
console.log('I should be true >> ', intercept(new Date("2018/01/01"), new Date("2018/01/05"), new Date("2018/01/03"), new Date("2018/02/03")))

Additional details: this code considers interception when intervals "touch" each other (like [1,2] and [2,4]). If you want to disconsider only touching, and consider only true overlap (like [1,3] and [2,4]), just remove the " + 1" inside the function. Suit yourself!

Again, applauses to the real source.

like image 21
Vladimir Brasil Avatar answered Dec 22 '25 14:12

Vladimir Brasil