Cesar Cervantes Cesar Cervantes - 1 year ago 116
PHP Question

user defined months added to given date

I am trying to add a user defined amount of months to the date previously added. $CustDate is already in YYYY-MM-DD format from previous form.

$CustDate=$_POST['formYear'] . "-" . $_POST['formMonth'] . "-" . $_POST['formDay'];

$d=strtotime("+" . $months . " Months");

$CustAddedDate=date("Y-m-d", strtotime($CustDate, $d));

If I enter the date as: 2016-08-04 as the $CustDate, it gives me the same value for the $CustAddedDate.

Where am I screwing this up? Thanks!

Answer Source

You add the + months along with the $CustDate. Provide the $Cusdate as the second argument in the addition.

$CustAddedDate = date('Y-m-d', strtotime("+" . $months . " Months", strtotime($CustDate)));
                                                                  // ^ add this with the addition

Or the DateTime variant:

$date = new DateTime($CustDate);
$date->modify('+ ' . $months . ' Month');
$CustAddedDate = $date->format('Y-m-d');
echo $CustAddedDate;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download