PHP显示小时范围,忽略过去的时间


PHP show range of hours and ignore past time

我试图使一个小脚本显示11:00和17:00之间的小时范围。11:00为起点,17:00为终点。到目前为止,我已经这样做了:

<?php
// Defining hours
$now = "13:00"; // <- my time now
$start_time = "11:00"; // start point
$end_time = "17:00"; // end point
// Convert to timestamps
$begin = strtotime($start_time);
$end = strtotime($end_time);
// Display range
while($begin <= $end) {
    echo date("H:i", $begin)." </br />";
    $begin = strtotime('1 hour', $begin);
}
?>

并成功输出起始点和结束点之间的范围:

11:00 
12:00 
13:00 
14:00 
15:00 
16:00 
17:00 

我的目标是使这个脚本显示的时间范围从13:00(我的时间),如果实际时间超过开始时间(11:00)。像这样:

11:00 hidden
12:00 hidden
13:00 
14:00 
15:00 
16:00 
17:00 

谁能建议一下怎么做?

在这种情况下,只需使用:

$present = strtotime($now);
if($present > $begin){  
    $begin  = $present;
}

但是如果你说$now = 18:00或以上,你需要什么

我认为你可以简化整个解决方案。不使用时间操作,为什么不简单地增加一个变量,从当前小时1117。要确定$begin,只需使用max(),如下所示:

$begin = max(date('H'), 11);
$end = 17;
while($begin <= $end) {
    echo $begin . ':00<br>';
    $begin++;
}

我已经添加了@user1234建议的小比特,现在它可以像我想要的那样工作。这里是完整的代码供参考。

<?php
// Defining hours
$now = "13:00"; // <- my time now
$start_time = "11:00"; // start point
$end_time = "17:00"; // end point
// Convert to timestamps
$actual = strtotime($now);
$begin = strtotime($start_time);
$end = strtotime($end_time);
// Added this to see if actual time is more than start time - creadit user1234
if($actual > $begin) {  
    $begin = $actual;
}
// Added this to see if actual time is more than 17:00
if($actual > $end) {  
    echo "Try tomorrow";
}
// Display ranges accordingly.
while($begin <= $end) {
    echo date("H:i", $begin)." </br />";
    $begin = strtotime('1 hour', $begin);
}
?>

如果需要,欢迎任何人测试和使用。