Skip to content
Advertisement

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

Just want to covert Jan to 01 (date format)

I can use array() but looking for another way…

Any suggestion?

Advertisement

Answer

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

3 People found this is helpful
Advertisement