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.

5
  • your code showing one result 100 times.where did you use $i ? Commented Nov 1, 2013 at 4:49
  • Cannot reproduce - codepad.viper-7.com/8wAdrh Commented Nov 1, 2013 at 4:50
  • possible duplicate of Adding days to $Date in PHP Commented Nov 1, 2013 at 4:52
  • Well, I don't use $i, but $x just for counting (in this code). Commented Nov 1, 2013 at 4:53
  • I have tested on PHP 5.4.19, PHP 5.3.1 (with XAMPP on Windows 8), and got the same result. So I decide to ask you guys. Commented Nov 1, 2013 at 4:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Consequentially, this takes care of the DST switch mentioned in Paul's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.