Javascript Date: Ensure getMinutes(), getHours(), getSeconds() puts 0 in front if necessary

前端 未结 3 820
走了就别回头了
走了就别回头了 2020-12-08 08:05

Looking for a creative way to be sure values that come from the getHours, getMinutes, and getSeconds() method for the javascript Date object return \"06\" inste

相关标签:
3条回答
  • 2020-12-08 08:09

    Update: ECMAScript 2017 (ECMA-262)

    padStart has been added to pad the beginning of a string with another string, where the first value is the length it should be and the second value being what to pad it with.

    For example:

    let d = new Date()
    let h = `${d.getHours()}`.padStart(2, '0')
    let m = `${d.getMinutes()}`.padStart(2, '0')
    let s = `${d.getSeconds()}`.padStart(2, '0')
    
    let displayDate = h + ":" + m + ":" + s
    // Possible Output: 09:01:34
    

    Pre-ECMAScript 2017

    As far as I know, there's not. And I do this all the time for converting dates to the XML dateTime format.

    It's also important to note that those methods you list return a number, not a string.

    You can, of course, add these yourself by modifying Date.prototype.

    Date.prototype.getHoursTwoDigits = function()
    {
        var retval = this.getHours();
        if (retval < 10)
        {
            return ("0" + retval.toString());
        }
        else
        {
            return retval.toString();
        }
    }
    
    var date = new Date();
    date.getHoursTwoDigits();
    
    0 讨论(0)
  • 2020-12-08 08:10

    Similar to @jdmichal's solution, posting because I'd prefer something a little shorter:

    function pad(n) { return ("0" + n).slice(-2); }
    
    pad(6); // -> "06"
    pad(12); // -> "12"
    

    Rather than add individual methods to Date.prototype, you could just add this method to Number.prototype:

    Number.prototype.pad = function (len) {
        return (new Array(len+1).join("0") + this).slice(-len);
    }
    
    // Now .pad() is callable on any number, including those returned by
    var time = date.getHours().pad(2) + ":"
             + date.getMinutes().pad(2) + ":"
             + date.getSeconds().pad(2);
    
    0 讨论(0)
  • 2020-12-08 08:13
    function pad2(number) {
    
         return (number < 10 ? '0' : '') + number
    
    }
    
    document.write(pad2(2) + '<br />');
    document.write(pad2(10) + '<br />');
    

    OUTPUT:

    02

    10

    0 讨论(0)
提交回复
热议问题