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

后端 未结 11 1607
既然无缘
既然无缘 2020-11-27 19:21

Just want to covert Jan to 01 (date format)

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

Any suggestion?

11条回答
  •  清酒与你
    2020-11-27 20:05

    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 :-D 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

提交回复
热议问题