Chris Hansen
Chris Hansen

Reputation: 8635

How to determine if two date ranges overlap?

I have the following dates in utc timestamps. I would like to know whether the two time ranges overlap. Here's the code that I have so far:

dateRangeOverlaps(aStart, aEnd, bStart, bEnd) {
   if (aStart <= bStart && bStart <= aEnd) return true; // b starts in a
   if (aStart <= bEnd   && bEnd   <= aEnd) return true; // b ends in a
   if (bStart <  aStart && aEnd   <  bEnd) return true; // a in b
   return false;
}

Unfortunately, when the start times or end times overlap, the function returns true. For example, if I have the times: 9 am to 11am and 11am to 1pm, these two times should not overlap, but the function returns true nonetheless.

Or if I have the time 8am to 11am and 11am to 1pm, it returns true.

How can I make it return false for the times above?

so

// 11:00
const aStart = 1641052800000;

// 11:30
const aEnd = 1641054600000;

// 9:00
const bStart = 1641045600000;

// 11:00
const bEnd = 1641052800000;

// should return false       
console.dir(dateRangeOverlaps(aStart, aEnd, bStart, bEnd))

Upvotes: 0

Views: 1095

Answers (1)

Coxxs
Coxxs

Reputation: 502

If you fill the example to the code (9 am to 11am and 11am to 1pm), you can easily see the reason:

dateRangeOverlaps(aStart, aEnd, bStart, bEnd) {
    if (9am <= 11am && 11am <= 11am) return true; // returns true
    // ...
}

I would change the logic to following to make it easier to read:

function dateRangeOverlaps(aStart, aEnd, bStart, bEnd) {
    // Make sure aStart is before bStart
    if (aStart > bStart) {
        // Exchange a and b
        [aStart, aEnd, bStart, bEnd] = [bStart, bEnd, aStart, aEnd]
    }

    // Check overlap
    return aEnd > bStart
}

See this answer for a more efficient method.

Upvotes: 2

Related Questions