Lee
Lee

Reputation: 1280

PHP add days on to a specific date?

I am feeling a bit thick today and maybe a little tired..

I am trying to add days on to a string date...

$startdate = "18/7/2011";

$enddate = date(strtotime($startdate) . " +1 day");
echo $startdate;
echo $enddate;

My heads not with it... where am i going wrong ?

Thanks

Lee

Upvotes: 3

Views: 12425

Answers (6)

satyawan
satyawan

Reputation: 507

try this one, (tested and worked fine)

date('d-m-Y',strtotime($startdate . ' +1 day'));
date('d-m-Y',strtotime($startdate . ' +2 day'));
date('d-m-Y',strtotime($startdate . ' +3 day'));
date('d-m-Y',strtotime($startdate . ' +30 day'));

Upvotes: 5

Sadee
Sadee

Reputation: 3180

First you have to change the date format by calling changeDateFormat("18/7/2011"): returns: 2011-07-18 if your parsing argument

function changeDateFormat($vdate){
    $pos = strpos($vdate, '/');
    if ($pos === false) return $vdate;
        $pieces = explode("/", $vdate);
        $thisday = str_pad($pieces[0], 2, "0", STR_PAD_LEFT);
        $thismonth = str_pad($pieces[1], 2, "0", STR_PAD_LEFT);
        $thisyear = $pieces[2];
        $thisdate = "$thisyear-$thismonth-$thisday";
        return $thisdate;
}

And this..

$startdate = changeDateFormat($startdate);
$enddate = date('Y-m-d', strtotime($startdate . "+".$noOfDays." day"));

Upvotes: 0

NickAldwin
NickAldwin

Reputation: 11754

Either

$enddate = date(strtotime("+1 day", strtotime($startdate)));

or

$enddate = date(strtotime($startdate . "+1 day"));

should work. However, neither is working with the 18/7/2011 date. They work fine with 7/18/2011: http://codepad.viper-7.com/IDS0gI . Might be some localization problem.

In the first way, using the second parameter to strtotime says to add one day relative to that date. In the second way, strtotime figures everything out. But apparently only if the date is in the USA's date format, or in the other format using dashes: http://codepad.viper-7.com/SKJ49r

Upvotes: 9

Mikulas Dite
Mikulas Dite

Reputation: 7941

This will work

$startdate = "18/7/2011";
$enddate = date('d/m/Y', strtotime($startdate) + strtotime("+1 day", 0));
echo $startdate;
echo $enddate;

First, the start date is parsed into integer, then the relative time is parsed.

You might also utilize the second parametr of strToTime:

$startdate = "18/7/2011";
$enddate = date('d/m/Y', strtotime("+1 day", strtotime($startdate)));

Upvotes: -1

PtPazuzu
PtPazuzu

Reputation: 2537

You're probably looking for strtotime($startdate . "+ 1 day") or something

Upvotes: 0

genesis
genesis

Reputation: 50982

first parameter of date() is format

d.m.Y G:i:s

for example

additionally, your $startdate is invalid

Upvotes: 0

Related Questions