Converting integers to monthnames in PHP

On several occasions I’ve had to look up methods for converting integers into monthnames in PHP. Most involve some form of calculation. Below you’ll find an example of that method along with possibly the easiest alternative you’ll ever find.

So first of all – why would you need to convert from an integer to a monthname? Well, let’s say you have a date provided in conventional shorthand such as 01/01/2009 (btw that’s 01/01/2009 if you’re American, lol). You want to show that date on your web page, but you want to present it in a slightly more readable format such as January 1, 2009 (just so the Americans and Europeans don’t get confused).

Many tutorials you’ll find will suggest using PHP’s mktime function (which converts the provided date into a UNIX timestamp), along with the date function (which converts the timestamp back into a readable format). Here’s an example of that method (but take note that this option should not be used, for reasons that will become apparent):

function monthName($month_int) {

$month_int = (int)$month_int;

$timestamp = mktime(0, 0, 0, $month_int);

return date(“F”, $timestamp);

}

So what’s happening here then? The first line of the function type casts the $month_int parameter to an integer. This has the advantage of ensuring that an integer is passed, rather than a string, and conveniently removes a leading zero if included. The second line uses mktime() to create a unix timestamp. The third processes that timestamp and returns the month name.

Be warned – the above method won’t always work correctly. Look closely at the mktime() function. The first three parameters set the hour, minutes and seconds to zero. That’s ok because we’re not interested in the time here. The fourth parameter sets the month to whatever integer we’ve provided.

However, there’s no fifth parameter (for day) which means php will automatically set the day to whatever the current day is. Where this goes awry is when the current day is the 31st and you’re in a month that has less than 31 days. In this instance the mktime function will roll over to the next ‘legal’ day. For example, if you’ve tried to plug in 04 for the month and the current date is the 31st, PHP will decide that you can’t possibly want April 31, since that date doesn’t exist, and will set your date to May 1 instead – and, hey presto, when you were expecting ‘April’ you done gone and got ‘May’ instead. The way around this is to set the day parameter to the 1st by default, as follows:

function monthName($month_int) {

$month_int = (int)$month_int;

$timestamp = mktime(0, 0, 0, $month_int, 1);

return date(“F”, $timestamp);

}

The above method is still not infallible, though: if you plug in 0 (zero) as your month integer, you’ll get ‘December’ back. So read on for a much easier, and relatively foolproof way  to get your monthname back.

By the way, if you’ve been given a shorthand date (01/01/2009), you might first need to split the date up so you can just get at that month integer. Check the end of the article for a method to do that if you don’t already know. For now let’s assume you’ve got that month integer ready and waiting for conversion.

Check out the following function:

function monthName($month_int) {

$month_int = (int)$month_int;

$months = array(“”,”January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”);

return $months[$month_int];

}

// call the function as follows to return the month name

monthName(3);

So what the devil’s going on this time? Well, the first line we already know about (see further above if you’ve just joined us). The second line creates a simple numerically indexed array of month names (the numerical index is added supermagically by PHP). Note that the first array entry is blank. This is because array indexing starts at zero rather than 1. Why this is an issue will be made clear… right now.

See, the last line of our function returns the array value that corresponds to the key provided – the key being the $month_int and the value being the month name. Since the array keys start at 0, if you throw a 2 into the function you’ll get the third value back: ‘February’. It’s a little clearer if we write out the array fully:

$months[0] = “”;

$months[1] = “January”;

$months[2] = “February”;

$months[3] = “March”;

… well you get the idea…

If we hadn’t left the first value blank then it would look like this:

$months[0] = “January”;

$months[1] = “February”;

$months[2] = “March”;

… etc

As you can see, plugging in 2 in this case would return March, which wouldn’t do at all.

If you want to save yourself some server side processing then here’s a javascript equivalent:

function js_monthName(month_int) {

var monthname = new

Array(“”, “January”, “February”, “March”, “April”, “May”,”June”, “July”, “August”, “September”, “October”, “November”, “December”);

document.write(monthname[month_int]);

}

// call the function as follows to return the month name

js_monthName(3);

Finally, I promised a quick method for extracting the month integer from a date string. This is slightly adapted from the official php page for the split() function:

$date = “30/04/1973″;

list($day, $month, $year) = split(‘/’, $date);

// get the month name

echo monthName($month);

The above takes the string, which is this case is in the format ‘day/month/year’ and splits it into its component parts using the forward slash (‘/’) as the delimiter. If the date is formatted differently then either change the order of the variables in list or change the delimited. For instance, if the date was, for some strange reason, formatted ’04:30:1973′ you’d go for:

$date = “04:30:1973″;

list($month, $day, $year) = split(‘:’, $date);

// get the month name

echo monthName($month);

Happy converting!

2 thoughts on “Converting integers to monthnames in PHP”

  1. Thank you – I had been using the mktime approach and had no problems until today (the 31st!)

Leave a Reply

Your email address will not be published. Required fields are marked *

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