0

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

Wilest
  • 1,820
  • 7
  • 36
  • 62
  • 1
    Does this answer your question? [Adding days to $Date in PHP](https://stackoverflow.com/questions/3727615/adding-days-to-date-in-php) – trauni Oct 23 '22 at 06:42
  • @trauni Well, not exactly. – nice_dev Oct 23 '22 at 06:52
  • The [date](https://www.php.net/manual/en/function.date.php) function in php returns a string, whereas [date_add](https://www.php.net/manual/en/datetime.add.php) expects a `DateTime` object. – trauni Oct 23 '22 at 07:07

1 Answers1

0

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

nice_dev
  • 17,053
  • 2
  • 21
  • 35