Calculate date difference and print these days

I would like to calculate the difference of two dates and print all dates between them, for example:

$data_inicio = new DateTime("08-02-2018");
$data_fim = new DateTime("10-03-2018");
($dateInterval = $data_inicio->diff($data_fim);
echo $dateInterval->days;

My return is : 30.

What I would like to have was the days that are in that range.

Example: 09-02-2018, 10-02-2018 ..... 09-03-2018 and etc.

How do I retrieve these values?

Author: novic, 2018-03-21

4 answers

You can interact on the two dates with a simple for, the Class DateTime , there is a method add that can be inserted a DateInterval for a new date with a value in its Constructor P1D, i.e. one more day on the date, example:

<?php

$data_inicio = new DateTime("2018-02-08");
$data_fim = new DateTime("2018-03-10");
$dateInterval = $data_inicio->diff($data_fim);
echo $dateInterval->days;
$datas = array();
for($i = $data_inicio; $i < $data_fim; $i = $data_inicio->add(new DateInterval('P1D')) )
{
    $datas[] = $i->format("d/m/Y");

}

print_r($datas);

Online Example Ideone

references:

 3
Author: novic, 2018-03-21 12:32:19

You can take a look at this class DatePeriod in the php.net:

$periodo = new DatePeriod(
     new DateTime('2018-02-08'),
     new DateInterval('P1D'),
     new DateTime('2018-03-10')
);

It will return you an array of DateTimes.

To iterate on them:

foreach ($periodo as $key => $value) {
    var_dump($value->format('d-m-Y'));
}

Example in IdeOne

Source: www.php.net/manual/en/class.dateperiod.php

 3
Author: David Alves, 2018-03-21 12:34:22

You can use a repeat loop. Just capture the return in days and use a for, for example:

$data_inicio = new DateTime("08-02-2018");
$data_fim = new DateTime("10-03-2018");
$dateInterval = $data_inicio->diff($data_fim);


for ($i = 1; $i < $dateInterval->days; $i++) {

    /* Cria um intervalo de 1 dia */
    $interval = date_interval_create_from_date_string("+1 days");

    /* Adiciona esse intervalo na variável $data_inicio e imprime na tela o resultado */
    echo $data_inicio->add($interval)
        ->format("d/M/Y"), PHP_EOL;
}

Demo at IdeOne

 2
Author: Valdeir Psr, 2018-03-21 12:21:27

Gustavo, I believe you need to perform the following code

<?php

$d1 = '2018-02-09';
$d2 = '2018-03-09';

$timestamp1 = strtotime( $d1 );
$timestamp2 = strtotime( $d2 );

$cont = 1;
while ( $timestamp1 <= $timestamp2 )
{
echo $cont . ' - ' . date( 'd/m/Y', $timestamp1 ) . PHP_EOL;
$timestamp1 += 86400;
$cont++;
}
?>
 0
Author: Gabriel Henrique, 2018-03-21 12:24:52