0

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.

pavel
  • 26,538
  • 10
  • 45
  • 61
RQEST
  • 107
  • 1
  • 9

4 Answers4

13

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");
}

?>
salathe
  • 51,324
  • 12
  • 104
  • 132
3

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
Marc
  • 3,683
  • 8
  • 34
  • 48
3
$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");
   }
splash58
  • 26,043
  • 3
  • 22
  • 34
2

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');
}
codeneuss
  • 905
  • 4
  • 12