Convert month name to a number

For the longest time, I’ve always come across this barrier. No pun intended. I wish there was an easier way to convert the month name to a number, but after searching, I came across this thanks to doodlebee from webmasterworld.

Here’s what we have as follows, just copy and paste it and obviously change the month name to whatever month you need and it’ll show up.

function getMonth($m) {
$monthnames = array(
01 => 'January',
02 => 'February',
03 => 'March',
04 => 'April',
05 => 'May',
06 => 'June',
07 => 'July',
08 => 'August',
09 => 'September',
10 => 'October',
11 => 'November',
12 => 'December');

for($i=1;$i<=12;$i++){
$i = sprintf("%02d",$i);
if(date("F", mktime(0, 0, 0, $i, 1, 0)) == $m){
$month_number = $i;
}
}
return $month_number;
}//end function

echo getMonth('March');
echo getMonth('December');

And vice versa

function getMonthNum($m) {
$monthnames = array(
'01' => 'January',
'02' => 'February',
'03' => 'March',
'04' => 'April',
'05' => 'May',
'06' => 'June',
'07' => 'July',
'08' => 'August',
'09' => 'September',
'10' => 'October',
'11' => 'November',
'12' => 'December');

return $monthnames[$m];
}//end function

echo getMonthNum('09');
This entry was posted in Code and tagged , , , , , . Bookmark the permalink.

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>