Javascript add leading zeroes to date

后端 未结 25 1870
执笔经年
执笔经年 2020-11-22 02:50

I\'ve created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:

var MyDate = new Date();
var MyDateString = new Date();
M         


        
25条回答
  •  灰色年华
    2020-11-22 03:27

    You could simply use :

    const d = new Date();
    const day = `0${d.getDate()}`.slice(-2);
    

    So a function could be created like :

    AddZero(val){
        // adding 0 if the value is a single digit
        return `0${val}`.slice(-2);
    }
    

    Your new code :

    var MyDate = new Date();
    var MyDateString = new Date();
    
    MyDate.setDate(MyDate.getDate()+10);
    MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
    

提交回复
热议问题