tags:

views:

219

answers:

3

My code to add one day to a date returns:

date before day adding: 2009-09-30 20:24:00 date after adding one day. SHOULD be rolled over to the next month: 1970-01-01 17:33:29

<?php

    //add day to date test for month roll over

    $stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00"));

    echo 'date before day adding: '.$stop_date; 

    $stop_date = date('Y-m-d H:i:s', strtotime('+1 day', $stop_date));

    echo ' date after adding one day. SHOULD be rolled over to the next month: '.$stop_date;
?>

Ive used pretty similar code before what am I doing wrong here?

+1  A: 

I always just add 86400 (seconds in a day):

$stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00") + 86400);

echo 'date after adding 1 day: '.$stop_date;

It's not the slickest way you could probably do it, but it works!

Doug Hays
Whats the slickest eh?.
ian
How do you deal with leap seconds when adding 86400 won't work as there's 86401 seconds in that day? (ok, I know it only happens every few years, but depending on the app this might be important)
Glen
Not all days have 86400 seconds in them. In fact, in most places in the US there are 3600 fewer or additional seconds twice a year.
Peter Kovacs
You can safely ignore leap seconds, since "Unix time" does. This is somewhat complicated, but read this article for more info: http://derickrethans.nl/leap_seconds_and_what_to_do_with_them.php
Christian Davén
+4  A: 
<?php
$stop_date = '2009-09-30 20:24:00';
echo 'date before day adding: ' . $stop_date; 
$stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' + 1 day'));
echo 'date after adding 1 day: ' . $stop_date;
?>
w35l3y
Thanks. Solved it as: $stop_date = date('Y-m-d H:i:s', strtotime( "$stop_date + 1 day" ));
ian
should work too. I don't like to use "
w35l3y
+1  A: 

While I agree with Doug Hays' answer, I'll chime in here to say that the reason your code doesn't work is because strtotime() expects an INT as the 2nd argument, not a string (even one that represents a date)

If you turn on max error reporting you'll see this as a "A non well formed numeric value" error which is E_NOTICE level.

Peter Bailey