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

后端 未结 11 1503
既然无缘
既然无缘 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 19:51
    var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    

    then just call monthNames[1] that will be Feb

    So you can always make something like

      monthNumber = "5";
      jQuery('#element').text(monthNames[monthNumber])
    
    0 讨论(0)
  • 2020-11-27 19:56
    function getMonthDays(MonthYear) {
      var months = [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December'
      ];
    
      var Value=MonthYear.split(" ");      
      var month = (months.indexOf(Value[0]) + 1);      
      return new Date(Value[1], month, 0).getDate();
    }
    
    console.log(getMonthDays("March 2011"));
    
    0 讨论(0)
  • 2020-11-27 19:59

    I usually used to make a function:

    function getMonth(monthStr){
        return new Date(monthStr+'-1-01').getMonth()+1
    }
    

    And call it like :

    getMonth('Jan');
    getMonth('Feb');
    getMonth('Dec');
    
    0 讨论(0)
  • 2020-11-27 19:59

    Here is a simple one liner function

    //ECHMA5
    function GetMonth(anyDate) { 
       return 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
     }
    //
    // ECMA6
    var GetMonth = (anyDate) => 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
    
    0 讨论(0)
  • 2020-11-27 20:03

    Another way;

    alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );
    
    0 讨论(0)
  • 2020-11-27 20:03

    Here is another way :

    var currentMonth = 1
    var months = ["ENE", "FEB", "MAR", "APR", "MAY", "JUN", 
                  "JUL", "AGO", "SEP", "OCT", "NOV", "DIC"];
    
    console.log(months[currentMonth - 1]);
    
    0 讨论(0)
提交回复
热议问题