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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With