0

I have the following simple PHP code:

$timeRange = new DatePeriod(
    new DateTime('09:00:00'),
    new DateInterval('PT30M'),
    new DateTime('18:00:00')
);

foreach ($timeRange as $time) {
    $options[$time->format('H:m')] = $time->format('H:m');
}

I am expecting to get a list of times out of this that starts at 09:00, 09:30, 10:00, 10:30... and every half hour to ...16:30, 17:00, 17:30, 18:00.

What I'm actually getting is this list of times:

09:10, 10:10, 11:10, 12:10, 13:10, 14:10, 15:10, 16:10, 17:10

As you can see, this is wrong on two counts: it is incrementing by an hour each time rather than half an hour, and it is starting at an arbitrary time ten minutes past the hour.

Both of these are consistent; it isn't based on the time I ran the code, for example.

I also tried adding a hard-coded date to the DateTime classes, so that they looked like this:

new DateTime('2018-01-01 09:00:00')

This changed the output such that all the results were one minute past the hour. Again, it incremented by an hour each time.

I can't explain this behaviour. It seems to be completely wrong. Can anyone explain it, and tell me what I need to do to fix this.

I can, of course, revert to using timestamps; I have code for this that works already. But I would like to know what is going on with the DatePeriod.

For reference, this is running under PHP 7.2.4.

Spudley
  • 166,037
  • 39
  • 233
  • 307

1 Answers1

3
$options[$time->format('H:m')] = $time->format('H:m');

m is the month identifier. You want i:

$options[$time->format('H:i')] = $time->format('H:i');
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98