PHP:如何在不使用日期的情况下检查特定范围内的时间?

时间:2016-08-25 16:29:27

标签: php time

直接举个例子,因为我在解释事情方面做得不好而且很抱歉。 那么例如你想检查具体时间是否在范围内?

sample range
- 20:00 - 05:00
result : 
  - 19:59 is false
  - 21:00 is true
  - 00:00 is true
  - 04:00 is true
  - 05:01 is false

- 07:00 - 16:00
result :
  - 06:59 is false
  - 09:00 is true
  - 12:00 is true
  - 16:01 is false

2 个答案:

答案 0 :(得分:0)

很难比较没有约会的时间。您也应该传递日期,否则无法验证例如04:00。 这是代码:

function in_time_range($start, $end, $check)
{
    $start = new DateTime($start);
    $end = new DateTime($end);
    $check = new DateTime($check);

    return $check >= $start && $check <= $end;
}

var_dump(in_time_range('25-08-2016 20:00:00', '26-08-2016 05:00:00', '25-08-2016 21:00:00')); // true
var_dump(in_time_range('25-08-2016 20:00:00', '26-08-2016 05:00:00', '26-08-2016 06:00:00')); // false

编辑:

以防万一 - 如果你从不同的日子里给出时间,这是不可能的。您的示例是22:0005:00,所以我告诉您要比较两个不同日期的时间。

如果您想比较同一天的时间,那么完全有可能使用以下代码:

function in_time_range($start, $end, $check)
{
    $start = new DateTime($start);
    $end = new DateTime($end);

    if ($end < $start) {
        $tmp = $start;
        $start = $end;
        $end = $tmp;
        unset($tmp);
    }

    $check = new DateTime($check);

    return $check >= $start && $check <= $end;
}

var_dump(in_time_range('20:00', '05:00', '19:00')); // true
var_dump(in_time_range('20:00', '05:00', '04:00')); // false

答案 1 :(得分:-3)

这是PHP和逻辑的代码,实际上它非常简单

<?php
echo "<pre>";
$startPush = "22:00";
$endPush = "17:30";
for($i = 0;$i < 24;$i++){
    $hour = str_pad($i, 2, "0", STR_PAD_LEFT);
    $timeNow = "{$hour}:00";
    $isOK = ($startPush <= $timeNow and $endPush >= $timeNow);
    if ($startPush > $endPush) {
        $bigTime = ($startPush <= $timeNow and "24:00" >= $timeNow);
        $litTime = ("00:00" <= $timeNow and $endPush >= $timeNow);
        $isOK = ($bigTime or $litTime);
    }

    echo "{$timeNow} is ".($isOK ? "PASS" : "ERROR")."<br>";
}

结果

00:00 is PASS
01:00 is PASS
02:00 is PASS
03:00 is PASS
04:00 is PASS
05:00 is PASS
06:00 is PASS
07:00 is PASS
08:00 is PASS
09:00 is PASS
10:00 is PASS
11:00 is PASS
12:00 is PASS
13:00 is PASS
14:00 is PASS
15:00 is PASS
16:00 is PASS
17:00 is PASS
18:00 is ERROR
19:00 is ERROR
20:00 is ERROR
21:00 is ERROR
22:00 is PASS
23:00 is PASS