I'm tring to get a list of dates and hours from one date to another.
To do that I'm using DateTime class and modify method to add 1 hour to the current dateTime. But something weird happens, the 02 hour of the 2022/03/27 (year/month/day) is not calculated.
Here's the test code (not the real code):
<?php
$from = new DateTime(date('2022/03/27 00:00:00'));
$to = new DateTime(date('2022/03/27 23:59:59'));
do {
echo $from->format('Y/m/d H') . "\n";
$from->modify(' 1 hour');
} while ($from->getTimestamp() < $to->getTimestamp());
And that's the results:
2022/03/27 00
2022/03/27 01
2022/03/27 03
2022/03/27 04
2022/03/27 05
2022/03/27 06
2022/03/27 07
2022/03/27 08
2022/03/27 09
2022/03/27 10
2022/03/27 11
2022/03/27 12
2022/03/27 13
2022/03/27 14
2022/03/27 15
2022/03/27 16
2022/03/27 17
2022/03/27 18
2022/03/27 19
2022/03/27 20
2022/03/27 21
2022/03/27 22
2022/03/27 23
Where is the "2022/03/27 02" ?
I'm using:
PHP 7.4.30 (cli) (built: Jun 27 2022 08:11:59)
Thanks.
CodePudding user response:
This seems to be because Daylight Savings Time comes into play at 2am on March 27th in your time zone.
$from = new DateTime(date('2022/03/27 00:00:00'));
$to = new DateTime(date('2022/03/27 23:59:59'));
do {
echo $from->format('Y/m/d H:i:s I') . "\n"; // with DST indicator
$from->modify(' 1 hour');
} while ($from->getTimestamp() < $to->getTimestamp());
produces
2022/03/27 00:00:00 0
2022/03/27 01:00:00 0
2022/03/27 03:00:00 1
2022/03/27 04:00:00 1
2022/03/27 05:00:00 1
2022/03/27 06:00:00 1
2022/03/27 07:00:00 1
2022/03/27 08:00:00 1
2022/03/27 09:00:00 1
2022/03/27 10:00:00 1
2022/03/27 11:00:00 1
2022/03/27 12:00:00 1
2022/03/27 13:00:00 1
2022/03/27 14:00:00 1
2022/03/27 15:00:00 1
2022/03/27 16:00:00 1
2022/03/27 17:00:00 1
2022/03/27 18:00:00 1
2022/03/27 19:00:00 1
2022/03/27 20:00:00 1
2022/03/27 21:00:00 1
2022/03/27 22:00:00 1
2022/03/27 23:00:00 1
CodePudding user response:
Thanks to @droopsnoot for the DST detail ;)
This code works fine:
<?php
$from = new DateTime(date('2022/03/30 00:00:00'), new DateTimeZone('UTC'));
$to = new DateTime(date('2022/03/30 23:59:59'), new DateTimeZone('UTC'));
do {
echo $from->format('Y/m/d H') . "\n";
$from->modify(' 1 hour');
} while ($from->getTimestamp() < $to->getTimestamp());