检查两个以上的日期范围是否重叠

2022-01-24 00:00:00 date compare range javascript

我有多个日期范围.我想检查它们是否在 javascript 中重叠.当只有两个时很容易,我使用:

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) {}

但是当日期范围超过 2 个时,公式是什么?

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

推荐答案

你可以使用嵌套的 for 循环和 arguments

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

相关文章