Get the last 12 months in PHP

后端 未结 5 1686
醉话见心
醉话见心 2020-12-14 16:46

So here is an interesting problem I learned today.

I need to populate an array with the last 12 months, starting with the past month. So in August 2011, the last 12

5条回答
  •  时光取名叫无心
    2020-12-14 17:12

    The joys of different month lengths. strtotime is being literally, and taking 'Aug 31' and tryinn to make "Sep 31", which doesn't exist. So you end up with Oct 1 or something. A safer approach is this:

    for ($i = 1; $i <= 12; $i++) {
        $months[] = date("Y-m%", mktime(0, 0, 0, $i, 1, 2011));
    }
    

    strtotime is magical sometimes, but it's not reliable and certainly not "fast".

提交回复
热议问题