William Truong
William Truong

Reputation: 247

PHP strtotime error when convert some date string to datetime value

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.

Upvotes: 2

Views: 1180

Answers (2)

Paul Creasey
Paul Creasey

Reputation: 28824

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

Upvotes: 4

Phil
Phil

Reputation: 164733

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>';
}

Upvotes: 3

Related Questions