Javascript add leading zeroes to date

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

    What I would do, is create my own custom Date helper that looks like this :

    var DateHelper = {
        addDays : function(aDate, numberOfDays) {
            aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
            return aDate;                                  // Return the date
        },
        format : function format(date) {
            return [
               ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
               ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
               date.getFullYear()                          // Get full year
            ].join('/');                                   // Glue the pieces together
        }
    }
    
    // With this helper, you can now just use one line of readable code to :
    // ---------------------------------------------------------------------
    // 1. Get the current date
    // 2. Add 20 days
    // 3. Format it
    // 4. Output it
    // ---------------------------------------------------------------------
    document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));

    (see also this Fiddle)

提交回复
热议问题