检查时间字符串是否超出小时数

时间:2018-09-18 10:34:28

标签: php

如果给定时间为$a = 22:15:00$b = 03:10:00

如何检查设置为19:00:0006:59:59的时间是否不足

这是从旧的4D数据库中迁移数据,因此时间不再是时间戳。

我当时在想这样的事情,但确实不确定。

$time = DateTime::createFromFormat('H i s', $a )->format('H:i:s');

if($time  >= "19:00:00") && ($time  <= "06:59:59") {
}

2 个答案:

答案 0 :(得分:1)

您可以将它们转换为时间戳,然后进行比较

$a = '22:15:00';
$b = '03:10:00';
$lower='06:59:59';
$upper='19:00:00';
$ts_a=strtotime(date('Y-m-d').$a);
$ts_b=strtotime(date('Y-m-d').$b);
$ts_lower=strtotime(date('Y-m-d').$lower);
$ts_upper=strtotime(date('Y-m-d').$upper);
if($ts_a<=$ts_upper && $ts_a>=$ts_lower){
    echo $a. " is in range";
}
else{
    echo $a. " is not in range";

}
if($ts_b<=$ts_upper && $ts_b>=$ts_lower){
    echo $b. " is in range";
}
else{
    echo $b. " is not in range";

}

答案 1 :(得分:1)

如果您纠正了一些语法错误并更改为OR条件,则您的代码实际上是有效的:

<?php
$borders['Top'] = "19:00:00";
$borders['Bottom'] = "06:59:59";

// here's your code packed into a function, so it can be tested:
function checkIfOutside($value, $borders) {
                             // missing : here
    $time = DateTime::createFromFormat('H:i:s', $value )->format('H:i:s'); 
              // this re-format isn't really needed in this case, it might though if you have other formats coming in

             // changed from && to || , removed a )
    if($time  >= $borders['Top'] || $time  <= $borders['Bottom']) {
        return "outside";
    } else {
        return "inside";
    }
}


// Test the function:    
$testValues = ["A" => "17:15:00", "B" => "03:10:00", "C" => "22:59:00", "D"=> "07:00:00"];

foreach ($testValues as $name => $value) {
    echo "$name: $value is " . checkIfOutside($value, $borders) . "<br>";

}

// Output:
A: 17:15:00 is inside
B: 03:10:00 is outside
C: 22:59:00 is outside
D: 07:00:00 is inside