0

I need to check whether an entered time range overlaps with another time range This thread PHP function to check time between the given range? gives a simple explanation on how to check if one date is with a range

I altered the second example function/if-case to the following:

    if(check_slot_range('2014-06-26 06:00:00','2014-06-26 10:00:00', '2014-06-26 07:00:00') OR check_slot_range('2014-06-26 06:00:00','2014-06-26 10:00:00', '2014-06-26 09:00:00')){
      echo "OVERLAP";
    }else{
      echo "NO OVERLAP";
    }

Only the following give an overlap:

  • Range '2014-06-26 07:00:00' to '2014-06-26 09:00:00'

  • Range '2014-06-26 05:00:00' to '2014-06-26 09:00:00'

  • Range '2014-06-26 07:00:00' to '2014-06-26 11:00:00'

This one does not throw the overlap:

  • Range '2014-06-26 05:00:00' to '2014-06-26 11:00:00'

How do I need to change the if-clause to catch the overlap for the last example?

For clarification, here the function to compare

    function check_slot_range($start_date, $end_date, $todays_date)
{

  $start_timestamp = strtotime($start_date);
  $end_timestamp = strtotime($end_date);
  $today_timestamp = strtotime($todays_date);

  return (($today_timestamp >= $start_timestamp) && ($today_timestamp <= $end_timestamp));


}
Community
  • 1
  • 1
PrimuS
  • 2,505
  • 6
  • 33
  • 66

1 Answers1

1

To check for an overlap, you simply check if low1 <= high2 AND high1 >= low2 (instead of date >= low AND date <= high as in the example above)

You can thus create a new function that checks for this condition like this:

function check_ranges_overlap($start_date_1, $end_date_1, $start_date_2, $end_date_2)
{
    $start_timestamp_1 = strtotime($start_date_1);
    $end_timestamp_1 = strtotime($end_date_1);
    $start_timestamp_2 = strtotime($start_date_2);
    $end_timestamp_2 = strtotime($end_date_2);

    return (($start_timestamp_1 <= $end_timestamp_2) && ($end_timestamp_1 >= $start_timestamp_2));
}
jcaron
  • 17,302
  • 6
  • 32
  • 46
  • Sorry, could you specify that with the numbers/datetimes from above, I don't really know what low/high should be, as I also can't find " date >= low AND date <= high" in my clause. Thanks – PrimuS Jun 28 '14 at 02:23
  • almost perfect, thanks so far, but: Timestamps with same start or end will be "NO OVERLAP" e.g. exisiting timerange 08:00 to 08:10 --> 08:00 to 08:15 = "NO OVERLAP". I tried various return options, can't seem to get it right... – PrimuS Jun 28 '14 at 21:46
  • Just tested `check_ranges_overlap('2014-01-01 08:00:00','2014-01-01 08:10:00','2014-01-01 08:00:00','2014-01-01 08:15:00');` and it does return true as expected. What values exactly did to pass to the function? – jcaron Jun 28 '14 at 21:55
  • not sure what happened, I think it was related to my MySQL-DB, there were already duplicate entries, TRUNCATE helped, now it works! Thanks a million! – PrimuS Jun 28 '14 at 22:04