mtmacdonald
mtmacdonald

Reputation: 15070

How to list the last N months with PHP DateTime

I want to populate a select input with the last 5 months (including the current month). So on 09/04/2014 the options should look something like this:

April 2014
March 2014
February 2014
January 2014
December 2013

My first solution with PHP DateTime seemed to work:

for ($i = 0; $i < 5; $i++) {
 $date = new DateTime($i.' months ago');
 echo $date->format('F Y'); //populate select input
}

But in fact it doesn't handle edge cases. For example, on 31/03/2014 it produces:

March 2014
March 2014
January 2014
December 2013
December 2013

What is the correct way to list the last 10 months with PHP DateTime?

Upvotes: 2

Views: 851

Answers (2)

Glavić
Glavić

Reputation: 43552

You are getting same 2 months, because when you are subtracting 1 month from date, that has more days than previous month. Example: when you subtract 1 month from 31.3. you will get 3.3. (same month), and not 28.2. as you might expect...

My suggestion is to get first day of current month, and then do your logic:

$dt = new DateTime('first day of this month');
for ($i = 1; $i <= 10; $i++) {
    echo $dt->format('F Y'), "\n";
    $dt->modify('-1 month');
}

demo

Upvotes: 1

f.arcarese
f.arcarese

Reputation: 96

$date = new DateTime("2014/03/31");
for ($i = 0; $i <= 9; $i++) {
    $date->modify("-1 month");
    echo $date->format('F Y'); //populate select input
}

Upvotes: 2

Related Questions