PHP/值之间的小时数列表


PHP / List of the hours between values

我有两个变量

$a = '09:00'
$b = '13:00' 

告诉我如何获得列表:

9:00
10:00
11:00
12:00

无端13:00

谢谢。

您可以使用DatePeriod类在两次之间轻松循环,在这种情况下,间隔为1小时。

<?php
$a = '09:00';
$b = '13:00';
$period = new DatePeriod(
    new DateTime($a),
    new DateInterval('PT1H'),
    new DateTime($b)
);
foreach ($period as $date) {
    echo $date->format("H:i'n");
}
?>
$a = '09:00';
$b = '13:00';
$s = strtotime($a);
$e = strtotime($b);
while($s < $e) {
   echo date ("h:i", $s) . "'n";
   $s = strtotime (date ("h:i", $s) . " +1 hour");
   }

我会用for循环来完成:)

$a = '09:00';
$b = '13:00';
// convert the strings to unix timestamps
$a = strtotime($a);
$b = strtotime($b);
// loop over every hour (3600sec) between the two timestamps
for($i = 0; $i < $b - $a; $i += 3600) {
  // add the current iteration and echo it
  echo date('H:i', $a + $i).'<br>';
}

输出:

09:00
10:00
11:00
12:00

使用''DateTime的解决方案是:

$a = '09:00';
$b = '13:00';
$dtStart = 'DateTime::createFromFormat('H:i',$a);
$dtEnd = 'DateTime::createFromFormat('H:i',$b);
while($dtStart<$dtEnd){
    echo $dtStart->format('H:i') . PHP_EOL;
    $dtStart->modify('+ 1 Hour');
}