简体   繁体   中英

Detect overlapping time ranges in PHP

在此处输入图片说明

I want to see if time ranges overlap, if they do, true should be returned, otherwise false. If I have selected this time range:

10:30:00 - 11:30:00

then I need to check if it doesn't overlap another time range. For example:

10:30:00 - 11:30:00 overlaps with 10:30:00 - 12:30:00 so I have to disable the slot but I don't know how to do the comparison correctly.

I have the following function, but I think it doesn't work as I want it to work.

  $as = $selectedSlot['slot_start'];
  $ae = $selectedSlot['slot_end'];
  $bs = $DB_slots['slot_start'];
  $be = $DB_slots['slot_end'];


function checkSlotRange($as,$ae,$bs,$be){
  $as = strtotime($as);
  $ae = strtotime($ae);
  $bs = strtotime($bs);
  $be = strtotime($be);
  if($as <= $bs && $ae <= $be){
    return true;
  }else{
  return false;
  }  
}

You had the time checking logic wrong. You need to check that A's start time is later than B's start time, AND A's end time is earlier than B's end time.

<?php
function checkSlotRange($as,$ae,$bs,$be){
    $as = strtotime($as);
    $ae = strtotime($ae);
    $bs = strtotime($bs);
    $be = strtotime($be);
    return ($as >= $bs && $ae <= $be); 
}
var_dump(checkSlotRange("10:30", "11:30", "09:30", "12:30")); // true
var_dump(checkSlotRange("10:30", "11:30", "11:40", "12:30")); // false

Demo

I don't know if your time ranges go over midnight, but if they do, you need to add the day to the timestamp to do the comparison, otherwise you'll get unexpected results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM