some_id
some_id

Reputation: 29906

Check if time between 2 dates intersects time between 2 other dates

What is an efficient way to check if anywhere between 2 dates intersects anywhere between 2 other dates without having to check each second in between dates and checking if the second is in between the other two dates?

Upvotes: 1

Views: 237

Answers (4)

LSerni
LSerni

Reputation: 57453

What is an efficient way to check if anywhere between 2 dates intersects anywhere between 2 other dates without having to check each second in between dates and checking if the second is in between the other two dates?

You do it the other way. When is it that the first interval doesn't intersect the second?

  • When End1 < Start2 (the first interval ends before the second starts)
  • When Start1 > End2 (the first interval starts after the second has ended).

So you want

 End1 < Start2 OR Start1 > End2  // Condition of non-intersection

to be false: i.e. you want

 End1 >= Start2 AND Start1 <= End2   // Negation of above

to be true.

Upvotes: 1

Martin R
Martin R

Reputation: 540135

Two intervals [a, b] and [c, d] have a non-empty intersection if

a <= d && c <= b

therefore you can check

[a compare:d] <= 0 && [c compare:b] <= 0

to see if the intervals have any value in common.

(Here I have assumed that the intervals are ordered, i.e. that a <= b and c <= d.)

Upvotes: 1

Mundi
Mundi

Reputation: 80271

Your problem can be rephrased like this.

Check if any of two dates c1 and c2 are in between the two dates d1 and d2.

// assuming d1 is before d2
BOOL intersects = 
   ([d1 compare:c1] == NSOrderedAscending  &&
    [d2 compare:c1] == NSOrderedDescending)
    ||
   ([d1 compare:c2] == NSOrderedAscending &&
    [d2 compare:c2] == NSOrderedDescending)
    || [d1 compare:c1] == NSOrderedEqual
    || [d1 compare:c2] == NSOrderedEqual
    || [d2 compare:c1] == NSOrderedEqual
    || [d2 compare:c2] == NSOrderedEqual;

EDIT: alternatively,

NSTimeInterval i = [d2 timeIntervalSinceDate:d1];
NSTimeInterval c1i = [c1 timeIntervalSinceDate:d1];
NSTimeInterval c2i = [c2 timeIntervalSinceDate:d1];
BOOL intersects = (c1i >= 0 && c1i <= i) || (c2i >= 0 && c2i <= i); 

Upvotes: 1

MANIAK_dobrii
MANIAK_dobrii

Reputation: 6032

Say you have: time t and intervals [a-b] [c-d], if they are sorted like:

  • a < d
  • a < b
  • c < d

Then you may check if tis inside b and c, and the check if b > c, then the whole thing is true, else - no. And as a fast sight, I can't yet think up something better then full check if they are not sorted.

Upvotes: 1

Related Questions