简体   繁体   中英

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

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

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'));

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('Ym-d', strtotime($startdate . "+".$noOfDays." day"));

first parameter of date() is format

dmY G:i:s

for example

additionally, your $startdate is invalid

你可能正在寻找strtotime($startdate . "+ 1 day")或其他东西

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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM