Get month in mm format in javascript

前端 未结 9 886
悲&欢浪女
悲&欢浪女 2020-12-31 02:03

How do I retrieve the month from the current date in mm format? (i.e. \"05\")

This is my current code:

var currentDate = new Date();
va         


        
相关标签:
9条回答
  • 2020-12-31 02:22

    In order for the accepted answer to return a string consistently, it should be:

    if(currentMonth < 10) {
        currentMonth = '0' + currentMonth;
    } else {
        currentMonth = '' + currentMonth;
    }
    

    Or:

    currentMonth = (currentMonth < 10 ? '0' : '') + currentMonth;
    

    Just for funsies, here's a version without a conditional:

    currentMonth = ('0' + currentMonth).slice(-2);
    

    Edit: switched to slice, per Gert G's answer, credit where credit is due; substr works too, I didn't realize it accepts a negative start argument

    0 讨论(0)
  • 2020-12-31 02:23

    An alternative way:

    var currentMonth=('0'+(currentDate.getMonth()+1)).slice(-2)
    
    0 讨论(0)
  • 2020-12-31 02:23

    ES6 version, inpired by Gert Grenander

    let date = new Date();
    let month = date.getMonth()+1;
    month = `0${month}`.slice(-2);
    
    0 讨论(0)
  • 2020-12-31 02:24
    if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
    
    0 讨论(0)
  • 2020-12-31 02:31
    var CurrentDate = new Date();
        CurrentDate.setMonth(CurrentDate.getMonth());
    
        var day = CurrentDate.getDate();
        var monthIndex = CurrentDate.getMonth()+1;
        if(monthIndex<10){
            monthIndex=('0'+monthIndex);
        }
        var year = CurrentDate.getFullYear();
    
        alert(monthIndex);
    
    0 讨论(0)
  • 2020-12-31 02:34

    One line solution:

    var currentMonth = (currentDate.getMonth() < 10 ? '0' : '') + currentDate.getMonth();
    
    0 讨论(0)
提交回复
热议问题