Ed Price is Hungry

(but not very often)

Tip: Always look where you are going

Converting integers to monthnames in PHP

It's a new year and a whole twelve months of brand new dates, so what better than a quick and easy tutorial all about converting months from integers to proper month names?

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!

Posted:  January 04, 2010 at 08:51

Filed under: Web Design

Author: Justin

Last edit: February 24, 2010 - 15:43

No comments

Add a comment

HTML code is NOT allowed and will be stripped out.

Please enter the sum of two plus six in digits (e.g '19')

Search

Recently posted
Categories
Tags
Monthly Archives

Feeds RSS logo
Recent Twitterings...
  • RT @RichardGiles: there should be trials, like the ones they have for war crimes, for the people responsible for IE.
    March 10 at 08:49
  • @JoshuaWithers @uxintro ok- look - how about simply J-Bang...?
    March 10 at 08:49
  • @JoshuaWithers @erinscales Bang Bang Withers works for me.... er, not in the chatting up sense of course...
    March 10 at 07:47
  • @sebsharp @JoshuaWithers isn't there a mule that leaves for Esperance every third day when the month ends in 'y'?
    March 09 at 22:01
  • @CinemaslaveJoe I see you've been banished to the attic following the mug debacle...
    March 09 at 20:38
  • follow me on Twitter
Copyright

The content on this blog is protected by a Creative Commons license. This is purely to stop people from doing nasty things with my words - in the unlikely event that you do want to reproduce any content here just ask

Creative Commons License

Ed Price Is Hungry by Justin Cawthorne is licensed under a Creative Commons Attribution-Non-Commercial-No Derivative Works 3.0 Unported License.
Based on a work at www.edpriceishungry.com