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);
1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

that is a good solution except it is not going to include the first date as the OP asked
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.