打印时间为晚上10点至凌晨3点


print time between 10pm to 3am

我有两个时间字符串,如下:

10pm
3am

我想打印上述字符串之间的时间,如:

10pm
11pm
12am
1am
2am
3am

PHP Code I tried:

<?php
$new_otime = strtotime(date('H:i',strtotime('10pm')));
$close_time = strtotime(date('H:i',strtotime("3am")));
do { ?>
<option value="<?php echo date("g a",$new_otime) ?>"><?php echo date("g a",$new_otime); ?></option>
<?php
$new_otime = $new_otime+=3600;                      
} while ($new_otime == $close_time);
?>

但是它在选择框中只响应10 pm。我如何在这些字符串之间一直进行回声呢?

我建议做一些工作来完成这个工作:

<?php
$new_otime = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d').' 10pm')));
$close_time = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d').' 3am')));
if($close_time < $new_otime){
  $close_time = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d',strtotime('+1 day')).'3am')));
}
do { ?>
<option value="<?php echo date("g a",$new_otime) ?>"><?php echo date("g a",$new_otime); ?></option>
<?php
$new_otime = $new_otime+=3600;                      
} while ($new_otime <= $close_time);
?>
  1. 检查结束时间是否较大
  2. 如果第二天不能到达
  3. new_otime小于close_time时的循环

你也可以尝试使用DateTime和DatePeriod:

$from = date_create_from_format('ha', '10pm');
//create 5 interations, each adds an additional hour
$dp = new DatePeriod($from, new DateInterval('PT1H'), 5);
/** @var DateTime $d */
foreach ($dp as $d) {
    echo $d->format('ha');
}

我希望这是你正在寻找的:

$time=22;
for($i=0;$i<6;$i++) {
echo date("g a",mktime($time+$i,0,0,09,21,2016))."<br>";
}

试试这个

$new_otime = "10pm";
$close_time = "3am";
$counter=0;
while(date("g a",strtotime($new_otime)+3600*$counter)<=date("g a",strtotime($close_time))){
     echo date("g a",strtotime($new_otime)+3600*$counter).'<br>';
     $counter++;
}

试试这个代码

    <?php
    $new_otime = "10pm";
    $close_time = "3am";
    $new_otime = strtotime(date_create_from_format("ha", $new_otime)->format("ha"));
    $close_time = strtotime(date_create_from_format("ha", $close_time)->format("ha"));
        do {
            ?>
            <option value="<?php echo date("ha", $new_otime) ?>"><?php echo date("ha", $new_otime); ?></option>
            <?php
            $new_otime = strtotime(date("ha", strtotime("+1 hours", $new_otime)));
        } while ($new_otime != $close_time);
        if ($new_otime == $close_time) {
            ?>
            <option value="<?php echo date("ha", $new_otime) ?>"><?php echo date("ha", $new_otime); ?></option>
    <?php } ?>