Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test whether two time ranges overlap?

I need to implement booking functionality and ensure that bookings don't overlap in a Rails app.

The cover? and between? methods aren't quite what I need. I have to ensure uniqueness of a time range when compared to other potential ranges on the same model, and do it efficiently.

I THINK it can be done using overlaps?. The problem is that this returns TRUE for something like this:

(1..5).overlaps?(5..9)
=> true

If I compared a booking that ended right when another started (3:30 - 4:00 versus 4:00 - 4:30), it would say they do overlap, but they technically don't. That would be a problem right?

ValidatesOverlap seems to handle the issue, including edge overlap.

Any suggestions?

like image 727
John Trichereau Avatar asked Mar 25 '14 15:03

John Trichereau


People also ask

How do you calculate overlap time?

Overlap = min(A2, B2) - max(A1, B1) + 1. In other words, the overlap of two integer intervals is a difference between the minimum value of the two upper boundaries and the maximum value of the two lower boundaries, plus 1.

How do you find overlapping time intervals in SQL?

Basically, a period can be represented by a line fragment on time axis which has two boundaries; starttime and endtime. To claim two time periods to be overlapping, they must have common datetime values which is between lower and upper limits of both periods.


1 Answers

def overlap?(x,y)
  (x.first - y.end) * (y.first - x.end) > 0
end

will work. The problem is that Interval uses >=, as you can see in "Test if two date ranges overlap in Ruby or Rails".

like image 82
Robert Krzyzanowski Avatar answered Sep 29 '22 08:09

Robert Krzyzanowski