Easiest way to convert month name to month number in JS ? (Jan = 01)

Just for fun I did this:

function getMonthFromString(mon){
   return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

Bonus: it also supports full month names 😀
Or the new improved version that simply returns -1 – change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){

   var d = Date.parse(mon + "1, 2012");
   if(!isNaN(d)){
      return new Date(d).getMonth() + 1;
   }
   return -1;
 }

Sry for all the edits – getting ahead of myself

Leave a Comment