Javascript add leading zeroes to date

后端 未结 25 1827
执笔经年
执笔经年 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:24

    You could use ternary operator to format the date like an "if" statement.

    For example:

    var MyDate = new Date();
    MyDate.setDate(MyDate.getDate()+10);
    var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
    

    So

    (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())
    

    would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.

    Edit: Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.

提交回复
热议问题