检查时间范围是否重叠

时间:2014-06-28 01:05:31

标签: php datediff

我需要检查输入的时间范围是否与另一个时间范围重叠 该线程PHP function to check time between the given range?给出了关于如何检查一个日期是否具有范围

的简单说明

我将第二个示例函数/ if-case更改为以下内容:

    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";
    }

只有以下内容给出重叠:

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

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

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

这个不会抛出重叠:

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

如何更改if-clause以捕获最后一个示例的重叠?

为了澄清,这里有比较功能

    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));


}

1 个答案:

答案 0 :(得分:1)

要检查重叠,您只需检查low1 <= high2 AND high1 >= low2(而不是上面示例中的date >= low AND date <= high

您可以创建一个新函数来检查这种情况:

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));
}