在PHP中使用间隔的范围时间

时间:2015-02-12 15:11:19

标签: php datetime

我正在用PHP创建每日计划程序,每30分钟我会写一个表格行并检查预约是否匹配。但是,我的预约时间有问题,例如我要检查时间:15:34:58 - 16:34:58,我在15:3016:00之间无法匹配。这是我的代码:

try {
    $inizio=new DateTime($r["data"]." ".$r["ora"]); // for me is 15:34:58
    $fine=new DateTime($r["data_fin"]." ".$r["ora_fin"]); // for me is 16:34:58
    $timetoCheck=new DateTime(date("Y-m-d")." ".$h.":".$m.":00"); //dinamically change in 15:30 16:00 and so on..
    $intervallo=new DateInterval("PT30M");
    $range=new DatePeriod($inizio, $intervallo, $fine);
    foreach ($range as $fase){
        if (($timetoCheck>=$inizio) and ($timetoCheck<=$fine)) {
            echo $fase->format("H:i:s")." ". $inizio->format("H:i:s")." - ".$fine->format("H:i:s")."<br/><a href='#' id='evento_".$r["key_id"]."'>".$r["titolo"]."</a><br/>";
        }
    }
} catch (Exception $ecc){
    $logger->error($ecc->getMessage());
}

1 个答案:

答案 0 :(得分:0)

尝试一种比较时间的不同方式?

$dateTime = new DateTime("15:40:10");
$startTime = new DateTime("15:30:00");
$endTime = new DateTime("16:00:00");
if ($dateTime->diff($startTime)->format('%R') == '-' && $dateTime->diff($endTime)->format('%R') == '+') {
    // current time is within the appointment period
} else {
    // current time is either before or after the appointment period
}

http://php.net/datetime.diff