bakerjr
bakerjr

Reputation: 397

How to detect if start and end date overlaps another start and end date in JavaScript?

I got both a start and end date object on an event object. I got another object with the same start and end date objects in it. How do I test if they overlap each other?

Upvotes: 1

Views: 2415

Answers (2)

Amarghosh
Amarghosh

Reputation: 59451

function doesOverlap(e1, e2)
{
  var e1start = e1.start.getTime();
  var e1end = e1.end.getTime();
  var e2start = e2.start.getTime();
  var e2end = e2.end.getTime();

  return (e1start > e2start && e1start < e2end || 
      e2start > e1start && e2start < e1end)
}

Upvotes: 3

duffymo
duffymo

Reputation: 308763

There are some edge cases to consider here, but if you have two ranges [b1, e1] and [b2, e2], then they overlap if:

  1. b1 <= b2 <= e1 or
  2. b1 <= e2 <= e1 or
  3. b2 <= b1 <= e2 or
  4. b2 <= e2 <= e2

I think those cover it.

Upvotes: 2

Related Questions