Period of days between two dates, when the final date is less than the initial

Asked

Viewed 296 times

3

In PHP when I try to return the running days of a month I only get the future days:

$inicio = new DateTime('2019-11-12'); 
$fim = clone $inicio;                   
$fim->add(new DateInterval('P1M')); // intervalo de 1 mês

$intervaloPeriodo = DateInterval::createFromDateString('1 day'); // período de 1 dia
$periodo = new DatePeriod($inicio , $intervaloPeriodo, $fim);

foreach ($periodo as $p) {
    echo $p->format("Y-m-d") . "<br />";    
}

The return of the above code are the dates in the interval of 1 month increasingly:

/*
 data exemplo: 2019-11-12
- 2019-11-12
- 2019-11-13
- 2019-11-14
- 2019-11-15
 ... 
- 2019-12-11

*/

But the loop I need is the past days of the month in question (decreasing):

/*
 data exemplo: 2019-11-12
- 2019-11-12
- 2019-11-11
- 2019-11-10
- 2019-11-09
 ... 
- 2019-10-13

*/

What happens is that the period works only if it is the period positive/later but I need the period negative/previous month-long.

Note: setting the day as -1 (DateInterval::createFromDateString('-1 day')) doesn’t work, it goes into a loop and does not return the expected result.

Does anyone know how to solve this problem or other way to implement this date period?

  • 1

    https://stackoverflow.com/a/2338289/4734177

  • 1

    Thank you very much!

1 answer

2

DatePeriod has a builder in which, instead of the final date, you pass the amount of recurrences (ie the amount of times the range will be applied).

So instead of passing the final date, just pass the amount of recurrences. As I am applying a negative interval of "minus 1 day", the amount of recurrences will be the amount of days between the initial and final dates:

$inicio = new DateTime('2019-11-12');
$fim = clone $inicio;
$fim->modify('-1 month'); // 1 mês antes
$diff = $fim->diff($inicio); // diferença entre as datas

// intervalo de "menos 1 dia"
$intervalo = DateInterval::createFromDateString('-1 day');
// aplica o intervalo de "menos 1 dia"
// a quantidade de recorrências é o "número de dias entre as datas - 1"
$periodo = new DatePeriod($inicio, $intervalo, $diff->days - 1);
foreach ($periodo as $p) {
    echo $p->format("Y-m-d") . "<br />";
}

This prints the dates from 12/11/2019 to 13/10/2019 (if I don’t subtract 1 from $diff->days, will also be printed the day 12/10/2019), in descending order:

2019-11-12
2019-11-11
2019-11-10
2019-11-09
...
2019-10-13

See here the code running.


Note: I used the method diff to calculate the difference between the dates, as a month may be 28, 29, 30 or 31 days, so depending on the dates involved, the total amount of days may vary.

Browser other questions tagged

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