Repeat a number of times in an interval of days

Asked

Viewed 58 times

0

I have this code that repeats a number of times the day of each week.

$hoje = new DateTime();
$semana = new DateInterval('P7D');
$repeticoes = 3;

// Printa primeira data antes de somar os dias
echo  $hoje->format('Y-m-d '.$_POST['hora_inicio'].":00".'') . "\n<br>";
echo  $hoje->format('Y-m-d '.$_POST['hora_final'].":00".'') . "\n<br><br>";



// Como já foi printada a primeira data, repete N-1 vezes
for ($i = 0 ; $i < $repeticoes - 1 ; $i++) {
    // Adiciona uma semana
    $hoje = $hoje->add($semana);
    // Printa data adicionada
echo $hoje->format('Y-m-d '.$_POST['hora_inicio'].":00".'') . "\n<br>";
echo  $hoje->format('Y-m-d '.$_POST['hora_final'].":00".'') . "\n<br><br>";          
 }

Exit from the above code

2018-11-09

2018-11-16

2018-11-23

My debt would be as follows:

How can I do to repeat the interval between days stipulating a deadline?

Example:

Today’s date: 09/11/2018

Number of times to repeat between days: 3

End date: 16/11/2018

I need you to print:

09/11/2018

12/11/2018

15/11/2018

1 answer

2


In these cases the ideal is to do with while, not that it is not possible to do with for, but the for is usually used with integers.

<?php
    $data = DateTime::createFromFormat('d/m/Y', '09/11/2018'); // Define a data inicial
    $fim = DateTime::createFromFormat('d/m/Y', '16/11/2018'); // Define a data final
    $intervaloDias = 3; // Define o intervalo de dias

    while ($data->format('Y-m-d') <= $fim->format('Y-m-d')) { // Verifica se a data é menor que a data final

        echo $data->format('Y-m-d ') . "\n"; // Escreve a data na tela

        $data = $data->add(new DateInterval('P'.$intervaloDias.'D')); // Incrementa a data
    }
?>

Upshot

2018-11-09
2018-11-12
2018-11-15

I built the code so that anyone can test it and see it working, then you will need to make some changes to suit the context of your code, are basic changes to assign the dates in the variables.

See working on Ideone.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.