2

I have a trouble with strtotime in php.

$j = "2013-10-27";
for ($x = 0; $x < 100; $x++) {
  $j = date('Y-m-d', strtotime($j) + 86400);
  echo ' '.$j.' <br/>';
}

As the code is self explained, it will add one day to $j and then display to browser. But when $j = "2013-10-27", it prints just one result ("2013-10-27"). If I change $j to another date, this does work, but also stucks at this date (and some other date).

I have written other code to do this work. But does anyone know why it fails, or my code is wrong?

Thank you.

William Truong
  • 237
  • 3
  • 12

2 Answers2

4

This is because you are in a timezone with daylight savings time, and on the 27th October at 1 AM the time reverted to midnight, making it a 25 hour day.

This can be reproduced by setting the timezone:

<?php
date_default_timezone_set('Europe/London');
$j = "2013-10-27";
for ($x = 0; $x < 100; $x++) {
  $j = date('Y-m-d', strtotime($j) + 86400);
  echo ' '.$j.' <br/>';
}

http://codepad.viper-7.com/uTbNWf

Paul Creasey
  • 28,321
  • 10
  • 54
  • 90
3

strtotime has too many limitations in my opinion. Use the more recent DateTime lib instead

$j = new DateTime('2013-10-27');
$interval = new DateInterval('P1D');
for ($x = 0; $x < 100; $x++) {
    $j->add($interval);
    echo $j->format('Y-m-d'), '<br>';
}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Consequentially, this takes care of the DST switch mentioned in [Paul's answer](http://stackoverflow.com/a/19721032/283366) – Phil Nov 01 '13 at 05:01