检查两次是否重叠 [英] Check if two times overlap

查看:74
本文介绍了检查两次是否重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想看看我从数据库读取的时间是否与用户提供的时间重叠.

I want to see if a time I read from a db overlaps with a time provided by a user.

我的数据库如下:

-----------------------------------------------
|organiser|meeting_start|meeting_end|boardroom|
-----------------------------------------------
| John Doe| 1340193600  | 1340195400| big     |
-----------------------------------------------

我的代码如下:

date_default_timezone_set('Africa/Johannesburg');
$from = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_start']);
$to = strtotime($_GET['meeting_date'] . ' ' . $_GET['meeting_end']);
$another_meeting = false;
$meeting_date = strtotime($_GET['meeting_date']);
$meeting_next = $meeting_date + 86400;

$result = mysql_query("SELECT meeting_start, meeting_end FROM admin_boardroom_booking WHERE boardroom = '" . $_GET['boardroom'] . "' AND meeting_start >= '" . $meeting_date . "' AND meeting_end < '" . $meeting_next . "'")or die(mysql_error());
while($row = mysql_fetch_array($result)) {
    $from_compare = $row['meeting_start'];
    $to_compare = $row['meeting_end'];

    $intersect = min($to, $to_compare) - max($from, $from_compare);
    if ( $intersect < 0 )
        $intersect = 0;

    $overlap = $intersect / 3600;
    if ( $overlap <= 0 ) {
        $another_meeting = true;
        break;
    }
}

if ($another_meeting)
    echo 'ERROR';

如果我故意键入两次重叠的时间,则不会回显错误.我在做什么错了?

If I type two overlapping times on purpose, it doesn't echo error. What am I doing wrong?

推荐答案

当且仅当以下条件中的至少一个成立时,两个时间段P1和P2重叠:

Two time periods P1 and P2 overlaps if, and only if, at least one of these conditions hold:

  1. P1在P2(P2.from <= P1.from <= P2.to)的开始和结束之间开始
  2. P2在P1(P1.from <= P2.from <= P1.to)的开始和结束之间开始
  1. P1 starts between the start and end of P2 (P2.from <= P1.from <= P2.to)
  2. P2 starts between the start and end of P1 (P1.from <= P2.from <= P1.to)

这将捕获部分重叠的时段以及一个完全覆盖另一个时段的时段.如果两个周期重叠,则其中一个周期必须始终在另一个周期内开始(或结束).

This will catch partly overlapping periods as well as periods where one completely covers the other. One of the periods must always start (or end) inside the other if they are overlapping.

所以$another_meeting的定义是:

$another_meeting = ($from >= $from_compare && $from <= $to_compare) ||
                   ($from_compare >= $from && $from_compare <= $to);

您可能希望将边界情况更改为严格<检查一个事件是否可以在与另一个事件完全相同的时间开始.

You may want to change the borderline cases to strict < checks if one event can start at the exact same time as another ends.

这篇关于检查两次是否重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆