Javascript add leading zeroes to date



  • 3 Answer(s)

    Here is the solution,

    var MyDate = new Date();
    var MyDateString;
     
    MyDate.setDate(MyDate.getDate() + 20);
     
    MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
                 + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
                 + MyDate.getFullYear();
    

    Try this code here, http://jsfiddle.net/xA5B7/.

    The .slice(-2) gives us the last two characters of the string.

    we can add “0” to the day or month, and just ask for the last two since those are always the two we want.

    This will be the output (“0” + “9”) // Giving us “09” when MyDate.getMonth() returns 9.

    Then adding .slice(-2) on that gives us the last two characters which is, (“0” + “9”).slice(-2)
    “09”

    Here, if MyDate.getMonth() returns 10, it will be,

    (“0” + “10”) // Giving us “010”

    The final adding of .slice(-2) gives us the last two characters

    (“0” + “10”).slice(-2)
    “10”

    Answered on December 1, 2018.
    Add Comment

    This is the example of given question,

    without having to extend Javascript’s Number prototype. The handy function they give as an example is follows,

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

    They are used in the 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:12
    
    Answered on December 1, 2018.
    Add Comment

    This will be the simple solution,

    function str_pad(n) {
        return String("00" + n).slice(-2);
    }
    
    Answered on December 1, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.