简体   繁体   English

在PHP中检测重叠的时间范围

[英]Detect overlapping time ranges in PHP

在此处输入图片说明

I want to see if time ranges overlap, if they do, true should be returned, otherwise false. 我想查看时间范围是否重叠,如果重叠,则应返回true,否则返回false。 If I have selected this time range: 如果我选择了这个时间范围:

10:30:00 - 11:30:00 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. 10:30:00-11:30:00与10: 30: 00-12:30:00重叠,因此我必须禁用广告位,但我不知道如何正确进行比较。

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. 您需要检查A的开始时间是否晚于B的开始时间,并且A的结束时间早于B的结束时间。

<?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. 我不知道您的时间范围是否超过午夜,但如果确实如此,则需要将时间添加到时间戳中以进行比较,否则会得到意外的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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