jsk
jsk

Reputation: 337

Adding days to specific day

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?

Upvotes: 24

Views: 73294

Answers (3)

antpaw
antpaw

Reputation: 15985

$NewDate = date('Y-m-d', strtotime('+7 days', strtotime($day)));

Upvotes: 16

Corey Ballou
Corey Ballou

Reputation: 43457

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:

Upvotes: 55

JonH
JonH

Reputation: 33143

From php.com binupillai2003

<?php
/*
Add day/week/month to a particular date
@param1 yyyy-mm-dd
@param1 integer
by Binu V Pillai on 2009-12-17
*/

function addDate($date,$day)//add days
{
$sum = strtotime(date("Y-m-d", strtotime("$date")) . " +$day days");
$dateTo=date('Y-m-d',$sum);
return $dateTo;
}

?> 

Upvotes: 2

Related Questions