检查时间是否落在时间范围内

时间:2016-06-15 07:53:16

标签: php

我有这种情况。假设我已经设置了下面的加班时间。它可以在阵列中。

Array     From       Until
[0]       5:00 AM    7:00 AM
[1]       6:00 PM    9:00 PM

然后,我会来加班加点。如何检查实际加班时间是否落在上述时间范围内?

例如,我来加班:

OT Start: 6:00 AM , OT End: 9:00 AM

所以,我会得到

OT Start Allowed  OT End Allowed
6:00 AM           7:00 AM

更多情况,如果

OT Start     OT End     OT Start Allowed     OT End Allowed
4:00 AM      6:30 AM    5:00 AM              6:30 AM
5:30 AM      8:00 AM    5:30 AM              7:00 AM
5:30 PM      8:00 PM    6:00 PM              8:00 PM
6:30 PM      9:30 PM    6:30 PM              9:00 PM
5:30 PM      9:30 PM    6:00 PM              9:00 PM
5:30 AM      7:00 PM    5:30 AM              7:00 AM
                        6:00 PM              7:00 PM
6:00 AM      10:00 PM   6:00 AM              7:00 AM
                        6:00 PM              9:00 PM

系统应如何处理该方案。任何人都知道如何在PHP中这样做?提前谢谢。

1 个答案:

答案 0 :(得分:2)

对于每对时间范围,即一个允许小时范围和实际小时数,您需要检查实际时间段在允许时间段结束之前开始并在其开始之后结束(或者可能在之后或之后,如果这是>=代替>的案例。然后你只需要采用最新的开始时间和最早的结束时间。

$permitted_hours = [["05:00", "07:00"], ["18:00", "21:00"]];

$claims = [["04:00", "06:30"], ["05:30", "08:00"], ["17:30", "20:00"],
    ["18:30", "21:30"], ["17:30", "21:30"], ["05:30", "19:00"], ["06:00", "22:00"]];

echo "OT Start  OT End  OT Start Allowed  OT End Allowed\n";
foreach ($claims as $claim) {
    $first_match = true;
    echo "$claim[0]     $claim[1]   ";
    foreach ($permitted_hours as $permitted) {
        if ($claim[0] < $permitted[1] && $claim[1] > $permitted[0]) {
            if (!$first_match) {
                echo "\n                  ";
            }
            $start = max($permitted[0], $claim[0]);
            $end = min($permitted[1], $claim[1]);
            echo "$start             $end";
            $first_match = false;
        }
    }
    echo "\n";
}
/*
OT Start  OT End  OT Start Allowed  OT End Allowed
04:00     06:30   05:00             06:30
05:30     08:00   05:30             07:00
17:30     20:00   18:00             20:00
18:30     21:30   18:30             21:00
17:30     21:30   18:00             21:00
05:30     19:00   05:30             07:00
                  18:00             19:00
06:00     22:00   06:00             07:00
                  18:00             21:00
*/