Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  42] [ 7]  / answers: 1 / hits: 37196  / 10 Years ago, tue, april 1, 2014, 12:00:00

I have multiple date ranges. I want to check if they are overlapping in javascript. When there are only two it is easy, I use:



if(start_times1 <= end_times2 && end_times1 >= start_times2) {}


But what is the formula when there are more than 2 date ranges?


More From » date

 Answers
49

You can use nested for loops with arguments


function dateRangeOverlaps(a_start, a_end, b_start, b_end) {
if (a_start <= b_start && b_start <= a_end) return true; // b starts in a
if (a_start <= b_end && b_end <= a_end) return true; // b ends in a
if (b_start < a_start && a_end < b_end) return true; // a in b
return false;
}
function multipleDateRangeOverlaps() {
var i, j;
if (arguments.length % 2 !== 0)
throw new TypeError('Arguments length must be a multiple of 2');
for (i = 0; i < arguments.length - 2; i += 2) {
for (j = i + 2; j < arguments.length; j += 2) {
if (
dateRangeOverlaps(
arguments[i], arguments[i+1],
arguments[j], arguments[j+1]
)
) return true;
}
}
return false;
}

[#71679] Sunday, March 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;