Javascript add leading zeroes to date

后端 未结 25 1860
执笔经年
执笔经年 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
    
    0 讨论(0)
  • 2020-11-22 03:30

    You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options. For more info visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

    var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
    var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
    console.log(date.toLocaleDateString(undefined,options));
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-11-22 03:34

    The new modern way to do this is to use toLocaleDateString, because it allows you not only to format a date with proper localization, but even to pass format options to archive the desired result:

    var date = new Date(2018, 2, 1);
    var result = date.toLocaleDateString("en-GB", { // you can skip the first argument
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
    });
    console.log(result); // outputs “01/03/2018”

    When you skip the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too.

    If you don't need to support old browsers like IE10, this is the cleanest way to do the job. IE10 and lower versions won't understand the options argument.

    Please note, there is also toLocaleTimeString, that allows you to localize and format the time of a date.

    0 讨论(0)
  • 2020-11-22 03:35
    Number.prototype.padZero= function(len){
     var s= String(this), c= '0';
     len= len || 2;
     while(s.length < len) s= c + s;
     return s;
    }
    

    //in use:

    (function(){
     var myDate= new Date(), myDateString;
     myDate.setDate(myDate.getDate()+10);
    
     myDateString= [myDate.getDate().padZero(),
     (myDate.getMonth()+1).padZero(),
     myDate.getFullYear()].join('/');
    
     alert(myDateString);
    })()
    
    /*  value: (String)
    09/09/2010
    */
    
    0 讨论(0)
  • 2020-11-22 03:35
    function pad(value) {
        return value.tostring().padstart(2, 0);
    }
    
    let d = new date();
    console.log(d);
    console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
    
    0 讨论(0)
提交回复
热议问题