1

I am getting the starting and ending dates from a form.
I need to put within an array all the date between the former two, including themselves.
I'm using a normal for loop and, at the same time, printing the result, to verify.
Everything appear to be alright.
But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.

This is the code:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff  = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;

$dates = array();

$addDay = $date1;

for ($i = 0; $i < $diffDays; $i++) {
    $dates[$i] = $addDay;
    date_add($addDay, date_interval_create_from_date_string("1 day"));
    echo "array: " . $i . "&nbsp;: " . date_format($dates[$i], 'Y-m-d');
}

print_r($dates);
Mithical
  • 603
  • 1
  • 17
  • 28
  • Possible duplicate of [PHP: Return all dates between two dates in an array](https://stackoverflow.com/questions/4312439/php-return-all-dates-between-two-dates-in-an-array) – mickmackusa Jun 20 '17 at 14:40

2 Answers2

1

PHP code demo

<?php

$dates = array();
$datetime1 = new DateTime("2013-03-15");
$datetime2 = new DateTime("2013-03-22");
$interval = $datetime1->diff($datetime2);
$days = (int) $interval->format('%R%a');
$currentTimestamp = $datetime1->getTimestamp();
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
for ($x = 0; $x < $days; $x++)
{
    $currentTimestamp = strtotime("+1 day", $currentTimestamp);
    $dates[] = date("Y-m-d H:i:s", $currentTimestamp);
}
print_r($dates);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

I would do it that way

$startDate =  new \DateTime("2017-03-15");
$endDate = new \DateTime("2017-03-22");

$dates = [];
$stop = false;
$date = $startDate;
while(!$stop){
    $dates[] = $date->format('Y-m-d'); // or  $dates[] = $date->format('Y-m-d H:i:s')
    $date->modify('+1 day');
    if($date->getTimestamp() > $endDate->getTimestamp()){
        $stop = true;
    }
}
print_r($dates);
Accountant م
  • 6,975
  • 3
  • 41
  • 61