The right way to generate months

I recently wrote this (partial) piece of PHP code to generate a list of months in a year:

for ($i=1; $i<=12; $i++) {
    $monthStamp = mktime(0, 0, 0, $i);
    echo date('F', $monthStamp);
}

Today, I suddenly have two “February”s in the list. Not Good. I missed the part in mktime()’s docs that say missing arguments will default to the current time, so the code was generating a timestamp for Feb 29 2010 (which mktime() interprets as Mar 1 2010).

So note to self—the fix is explicitly specifying the day of month (just “1” in this case):

for ($i=1; $i<=12; $i++) {
    $monthStamp = mktime(0, 0, 0, $i, 1);
    echo date('F', $monthStamp);
}

Leave a Reply