The Scenario Let’s say you have an instance of DateTime that represents a starting time, and you have a duration that, when added to the starting time, represents an ending time.
Let’s say you have two such things and you want to know if they overlap (or intersect, or collide). For instance:
- March 29, 2009 @ 10:00am; 120 minutes
- March 29, 2009 @ 11:00am; 90 minutes
In this example there’s one hour of overlap in which #1 stretches from 10:00am - 12:00pm and #2 stretches from 11:00am - 12:30pm.
How to detect this? I’m sure there’s many clever ways, this way is mine.
We’re Gonna Need More Monkeys
First, we need to monkey-patch some core classes. Monkey-patching is fun, it makes us feel
As an aside: it’s patently absurd that DateTime doesn’t have a built-in function for converting to a Time instance (which is layered atop the patently absurd need for Ruby to have three unique Date/Time classes… but that’s another rant)….
Anyhow, let’s monkey-patch DateTime so it can return itself as an instance of Time:
1 2 3 4 5
Now we need to alter Range to detect intersections with other ranges the way Array does with its & operator. We do this with Bill Siggelkow’s clever
1 2 3 4 5 6 7
Ta-da; monkey-patching complete.
DateTime is the VB.Net of Date/Time Classes You’ve likely inferred from the code above that we won’t be using DateTime for this jaunty action, but rather instances of Time. You’d be correct. DateTime is remarkably unsuited for this sort of thing. But since DateTime is so popular and prevalent that’s where we’ll start.
Our first moment of comparison will start right now to 60 minutes in the future:
1 2 3
Our second moment in time will start 30 minutes from now to 120 minutes in the future:
1 2 3 4
Free-range Comparison Now that we have our times, let’s convert them into ranges:
1 2 3
and compare them:
As of this writing the output is:
which indicates an overlap/intersection/collision between the two timespans, displayed as seconds. Had there been no collision,
nil would have been returned instead.