Monthly update for days 30 and 31 in a date range

Asked

Viewed 79 times

0

What’s wrong with my formula to get the result down? I wish it had worked for all day 31 and I was correcting the month that there was no day 31.

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

Upshot:

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
  • It is to stay fixed the day 30 or 31 this?

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 on IDEONE

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

Behold:

// 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');
  • Of course, :D+1

  • Thanks @rray. Someone formats the code for me, I’m in a hurry

Browser other questions tagged

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