lyborko lyborko - 1 month ago 5
PHP Question

Is adding seconds wrong way to browse through the time in PHP?

I iterate through time by adding 86400 (the count of seconds in the 1 day) to list the dates.

define("DAY_SEC", 86400);
for ($i = strtotime("2016-10-01"); $i<=strtotime("2016-11-05"); $i = $i + DAY_SEC){
echo Date("Y-m-d, H:i:s", $i). ' = '. $i . '<br/>';
}


But look on the date "2016-10-30". It is there twice but with different hours

2016-10-28, 00:00:00 = 1477605600
2016-10-29, 00:00:00 = 1477692000
2016-10-30, 00:00:00 = 1477778400 <- here
2016-10-30, 23:00:00 = 1477864800 <- here
2016-10-31, 23:00:00 = 1477951200


What do I wrong?

thanx

Answer

Do not add or subtract or do any other math with timestamps to calculate past or future dates. Your code will fail after 2016-11-05 in U.S. and some other time zones because that is the end of Daylight Saving Time this year. strtotime() is aware of this, so use it with "+1 day" or something similar:

for ($i = strtotime("2016-10-01"); $i<=strtotime("2016-11-05"); $i = strtotime("+1 day", $i)){
        echo Date("Y-m-d, H:i:s", $i). ' = '. $i . '<br/>';
}

It turns out 2016-10-30 is the end of Daylight Saving Time in many other places, so the time zone you are using is subject to that change.

Comments