Adding days to specific day

jsk picture jsk · Dec 17, 2009 · Viewed 57k times · Source

Many examples are about adding days to this day. But how to do it, if I have different starding day?

For example (Does not work):

$day='2010-01-23';

// add 7 days to the date above
$NewDate= Date('$day', strtotime("+7 days"));
echo $NewDate;

Example above does not work. How should I change the starding day by putting something else in the place of Date?

Answer

Corey Ballou picture Corey Ballou · Dec 17, 2009

For a very basic fix based on your code:

$day='2010-01-23';

// add 7 days to the date above
$NewDate = date('Y-m-d', strtotime($day . " +7 days"));
echo $NewDate;

If you are using PHP 5.3+, you can use the new DateTime libs which are very handy:

$day = '2010-01-23';

// add 7 days to the date above
$NewDate = new DateTime($day);
$NewDate->add(new DateInterval('P7D');
echo $NewDate->format('Y-m-d');

I've fully switched to using DateTime myself now as it's very powerful. You can also specify the timezone easily when instantiating, i.e. new DateTime($time, new DateTimeZone('UTC')). You can use the methods add() and sub() for changing the date with DateInterval objects. Here's documentation: