Javascript date - Leading 0 for days and months where applicable

前端 未结 9 2107
情话喂你
情话喂你 2020-12-15 05:07

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:

var myDate = new Date();
var prettyDate =(myDate.getFu         


        
9条回答
  •  悲哀的现实
    2020-12-15 05:40

    You will have to manually check if it needs a leading zero and add it if necessary...

    var m = myDate.getMonth();
    var d =  myDate.getDate();
    
    if (m < 10) {
        m = '0' + m
    }
    
    if (d < 10) {
        d = '0' + d
    }
    
    var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;
    

提交回复
热议问题