Home > Software engineering >  DateAdd Function in loop not adding days
DateAdd Function in loop not adding days

Time:10-23

I've tried various examples, but can't seem to add days to a date. What am I doing worng?

$DateForQuery = date('Y-m-d',strtotime($_POST['fromdate']));
echo $DateForQuery;
echo "<br>";


for($x = 1; $x <= $days; $x  )
{   
    $NewDateForQuery = date_add($DateForQuery, new DateInterval("P5D"));
    echo $x;
    echo "<br>";
    echo $NewDateForQuery;
}

Output:

enter image description here

CodePudding user response:

date_add expects first parameter to be a DateTime object and not a date string. So, create one. Also, when you loop inside, you can simply print the initial current datetime object since it mutates the object itself.

<?php

$DateForQuery = DateTime::createFromFormat('!Y-m-d',date('Y-m-d',strtotime($_POST['fromdate'])));

echo $DateForQuery->format('Y-m-d'),PHP_EOL;

$days = 4;

for($x = 1; $x <= $days; $x  ){   
    date_add($DateForQuery, new DateInterval("P5D"));
    echo $x, " ", $DateForQuery->format('Y-m-d'),PHP_EOL;
}

Online Demo

  • Related