Reputation: 49
Here is the original script
<?php
$monthToAdd = 36;
$d1 = DateTime::createFromFormat('Y-m-d', '2016-04-10');
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month = $month % 12;
if($month === 0)
$month = 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('d-m-Y');
?>
and here is the one that I edited
<?php
$y = 2016;
$m = 04;
$d = 10;
$monthToAdd = 36;
$d1 = DateTime::createFromFormat('Y-m-d', '$y-$m-$d');
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
$year += floor($monthToAdd/12);
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month = $month % 12;
if($month === 0)
$month = 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
$d2->setTime($d1->format('H'), $d1->format('i'), $d1->format('s'));
echo $d2->format('d-m-Y');
?>
it give error
Idea is to add X value as month , show the result. For example the date provided is "2016-04-10" and $monthToAdd = 4; , it should give a result of 2016-08-10
script was working , but I just want to add a form so that user can input month to calculate. I am new to php, anyone help ?
Upvotes: 0
Views: 4557
Reputation: 589
Try to change this
$d1 = DateTime::createFromFormat('Y-m-d', '$y-$m-$d');
to
$d1 = DateTime::createFromFormat('Y-m-d', "$y-$m-$d");
php won't parse values inside of ' but it will inside of "
Hope that helps, if not, could you please pass on the exact error, and the line that it references.
Upvotes: 1
Reputation: 1036
In order for php to parse variables within stings properly, you must wrap them in double quote marks (").
Change
$d1 = DateTime::createFromFormat('Y-m-d', '$y-$m-$d');
to
$d1 = DateTime::createFromFormat('Y-m-d', "$y-$m-$d");
Upvotes: 2