How to get the correct month name using PHP

3:07pm, 31st October 2007

Can you see anything wrong in the following image?

Screenshot of james.lab6.com showing mktime bug

Persistent readers will notice that it’s part of the sidebar on this site’s main page, except slightly wrong. It turns out I have a bug that only occurs at the end of months! The following code is wrong:

date('F', mktime(0,0,0,$month))

The following code is right:

date('F', mktime(0,0,0,$month,1))

Why? It’s down to PHP being clever, and me being dumb (or possibly the other way round; it’s hard to tell with PHP).

The mktime function constructs a timestamp from the arguments you give it, filling in any missing arguments with the current local date and time. I guess this might be useful in some circumstances, but if you call it on, say, the 31st of October, when trying to use it to map 9 to September, the mktime function uses 31 for $day, and clearly there’s no such time as the 31st of September, so PHP decides to be clever by overflowing to the 1st of October. Similarly, attempting to map 2 to February when on the 31st of October overflows to the 3rd of March. Lovely.

The fix is to specify 1 for the day, since there’s always a first of the month.

The number one search result for “php get month name” currently recommends the wrong code. Google’s Code Search shows that this flawed idiom has already infiltrated a number of open source projects.

But now for the important part: there is a fixed version of my Wordpress theme!


Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Please enter the following words to prove your humanity: