Javascript add leading zeroes to date

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

    Here is an example from the Date object docs on the Mozilla Developer Network using a custom "pad" function, without having to extend Javascript's Number prototype. The handy function they give as an example is

    function pad(n){return n<10 ? '0'+n : n}
    

    And below is it being used in context.

    /* use a function for the exact format desired... */
    function ISODateString(d){
        function pad(n){return n<10 ? '0'+n : n}
        return d.getUTCFullYear()+'-'
        + pad(d.getUTCMonth()+1)+'-'
        + pad(d.getUTCDate())+'T'
        + pad(d.getUTCHours())+':'
        + pad(d.getUTCMinutes())+':'
        + pad(d.getUTCSeconds())+'Z'
    }
    
    var d = new Date();
    console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
    

提交回复
热议问题