Monthly update for days 30 and 31 on a date range

0

What's wrong with my formula to get the result down? I wanted it to work for every day 31 and to correct the month that there was not 31.

for ($i = 0 ; $i <= 12 ; $i++){
    $tempo = strtotime('03/31/1990'.'+'.$i.' month');
    echo date('d/m/Y', $tempo);
    echo '<br>';
}

Result:

31/03/1990
01/05/1990
31/05/1990
01/07/1990
31/07/1990
31/08/1990
01/10/1990
31/10/1990
01/12/1990
31/12/1990
31/01/1991
03/03/1991
31/03/1991
    
asked by anonymous 24.11.2015 / 17:23

1 answer

7

The correct way to do this would be to use DateInterval or DatePeriod .

See a small example:

$start    = new DateTime('2010-12-02');
$end      = new DateTime('2012-05-06');
$interval = DateInterval::createFromDateString('1 month');
$period   = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format('d/m/Y');
}

See working at IDEONE

Another way to know the last day of a month is to use the string last day of this month .

See:

// pega do mês atual
date('d/m/Y', strtotime('last day of this month')); 

Or

$date = DateTime::createFromFormat('m/Y', '01/2015');
$date->modify('last day of this month');
echo $date->format('d/m/Y');
    
24.11.2015 / 17:24