Calculate date difference and start these days

2

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 this range.

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

How do I recover these values?

    
asked by anonymous 21.03.2018 / 13:12

4 answers

3

You can interact on both dates with a simple for , the class DateTime , exists a add method that can be inserted into a DateInterval for a new date with a value in its constructor P1D , that is, an extra 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 Ideone Example

References:

21.03.2018 / 13:23
3

You can take a look at this class DatePeriod in 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 through them:

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

Example on IdeOne

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

    
21.03.2018 / 13:23
2

You can use a loop of repetition. Just capture the return in days and use 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;
}

Demonstration at IdeOne

    
21.03.2018 / 13:21
0

Gustavo, I think you need to make 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++;
}
?>
    
21.03.2018 / 13:24