Archive for December, 2008

Dec 07 2008

php date add alternative to date_add

Published by admin under php

Here’s one for you Sukie…

The php function date_add ( DateTime $object , DateInterval $interval ) is an experimental function and shouldn’t really be used in a production site.  The way to get around this is to use strtotime ( string $time [, int $now ] ).

If you’re trying to add a week to today’s date you can simply do the following:
$new_date = strtotime("+1 week");

but if need to add a week to a time stamp of your own you can do:
$my_date = strtotime('05-Dec-2008');
$new_date = strtotime("+1 week", $my_date);

Note: The second parameter needs to be a valid date, when I’m getting data from a database I will usually get the date in to a dd-mmm-yyyy format as this explicitly defines the date. If it were written ‘05-12-2008′ it potentially could be interpreted as ‘12-May-2008′ which could then cause other issues to your data further down the line.

You could condense the code to be one line:
$new_date = strtotime("+1 week", strtotime('05-Dec-2008'));

For outputting the $new_date I’d use php’s date ( string $format [, int $timestamp ] ) function:
$new_date = strtotime("+1 week", strtotime('05-Dec-2008'));
echo date('d M Y', $new_date)

 

Have a look at php’s strtodate function and php’s date function for information on how to use.

  

No responses yet