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

后端 未结 11 1504
既然无缘
既然无缘 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

    0 讨论(0)
  • 2020-11-27 20:10

    If you are using moment.js:

    moment().month("Jan").format("M");
    
    0 讨论(0)
  • 2020-11-27 20:10

    Here is a modified version of the chosen answer:

    getMonth("Feb")
    function getMonth(month) {
      d = new Date().toString().split(" ")
      d[1] = month
      d = new Date(d.join(' ')).getMonth()+1
      if(!isNaN(d)) {
        return d
      }
      return -1;
    }
    
    0 讨论(0)
  • 2020-11-27 20:12

    If you don't want an array then how about an object?

    var months = {
        'Jan' : '01',
        'Feb' : '02',
        'Mar' : '03',
        'Apr' : '04',
        'May' : '05',
        'Jun' : '06',
        'Jul' : '07',
        'Aug' : '08',
        'Sep' : '09',
        'Oct' : '10',
        'Nov' : '11',
        'Dec' : '12'
    }
    
    0 讨论(0)
  • 2020-11-27 20:16

    One more way to do the same

    month1 = month1.toLowerCase();
    var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
    month1 = months.indexOf(month1);
    
    0 讨论(0)
提交回复
热议问题