代码之家  ›  专栏  ›  技术社区  ›  Pentium10

如何检查一个时间范围是否在一组空闲时隙之下?

php
  •  1
  • Pentium10  · 技术社区  · 14 年前

    我有一个返回unixtime格式的空闲槽的方法 array['from','to']

    07:00 - 07:45
    07:45 - 08:30
    14:30 - 15:15
    15:15 - 16:00
    

    我想检查一个给定的范围是否在这些插槽下。它们可以重叠插槽,但不应跨越空闲插槽的周期。

    所以有效范围是:

    07:00 - 07:45
    07:00 - 08:30
    07:10 - 08:20 // also valid
    14:30 - 16:00 // also valid
    

    无效的范围是

    06:00 - 16:45
    15:15 - 16:10
    07:00 - 16:00 //there are no ranges between 8:30 and 14:30
    11:00 - 12:00
    

    编辑

    到目前为止,我要检查的是:

    $startsinfreeslot=true;
    $endrange=0;
    foreach ($arr as $slot) {
    $from=$slot['from'];
    $to=$slot['to'];
    if ($from==$start_date && $to==$end_date) {
        // given date matches a free slot
        return true;
    }
    if ($start_date>=$from && $start_date<$to) {
        $startsinfreeslot=true;
        $endrange=$to;
        continue;
    }
    
    if ($startsinfreeslot) {
        // we need to check if range continues
        if ($endrange==$from) {
            // range stops in the current range
            if ($end_date<=$to) {
                return true;
            } else {
                $endrange=$to;
                continue;
            }
        } else {
            // range doesn't continued return false
            return false;
        }
    }
    }
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   coolkid    14 年前

    假设代码的最后一行是:return false。
    你的代码需要检查另一个案例,为最后一个免费插槽。如果$start\u date>=$from和$end\u date<=$to($from和$to是最后一个槽位),则代码返回false。所以在循环之后,你应该检查最后一个插槽。