0

I would like to get an array containing strings like this: 2013-03, 2013-02, 2013-01, 2012-12, 2012-11... etc.

How would I go about it? I tried working with a loop and DateInterval class, but surprisingly 30.March -1month gives us 2.March, so that's not very useful.

$date = new DateTime();
$date->sub(DateInterval::createFromDateString('1 month'));

Thanks!

4

1 回答 1

1

Curiously, PHP returns the previous month of a date using the "next month" keyword :S

You can do the following:

<?php
$date = new DateTime();
// Subtract one month at a time
// until we reach 2009.
while ($date->format('Y') > 2009) {
    $date->sub(DateInterval::createFromDateString('next month'));
    var_dump($date->format('Y-m')); // Will print 2013-03 2013-02 [...]
};
?>
于 2013-03-30T20:03:08.217 回答