Main Content

Lots of way of converting 3 letter month abbreviations to numbers

Archive - Originally posted on "The Horse's Mouth" - 2010-09-10 11:19:42 - Graham Ellis

There are certain programming tasks that sound simple but end up fascinating ... they sound straightforward (and probably are), but it turns out there are lots of ways of doing them and you could spend a lot of time working out which was is best. One of those is converting three letter abbreviations for months into numbers. Sounds easy, doesn't it ... well - it is, but which way would you go?

a) A series of "if" and "elseif" statements

b) A string of 36 letters JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC and see where your month name appears in that

c) A switch statement with 12 choices (Obviously not available on languages that don't have a switch)

d) An array (Tcl), Hash (Perl), Table (Lua), Associative array (PHP) or dictionary (Python) where the keys are the names of the month and the values are the month numbers

e) A list (Tcl, Perl), Tuple (Python) , indexed array(PHP) indexed table (Lua) through which you search for the month string and return the index you're on when you find it.

I've put up a sample - in Lua - showing (a), (b) and (d) - it's [here] and comes from discussions on this week's course. There's no switch in Lua - and indeed the Lua user's Wiki sends you back to option (a) - see [here]. And option (e) is so inefficient and horrid that I'm not going to lower myself to write that code in Lua (note, though that the in operator in Python may make it acceptable there!