I have 2 variables
$a = '09:00'
$b = '13:00'
Tell me how to get a list:
9:00
10:00
11:00
12:00
without end 13:00
thanks.
You can use the DatePeriod
class to easily loop between the two times with, in this case, an interval of 1 hour.
<?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");
}
?>
I would do it with a for
loop :)
$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>';
}
Output:
09:00
10:00
11:00
12:00
$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");
}
The solution using \DateTime is:
$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');
}