Leading zeros in minutes

后端 未结 5 1893
眼角桃花
眼角桃花 2020-12-31 17:20

I created a clock to be placed in the header of my website. The time is not displaying a zero for minutes < 10. For example if the time is 10:50, it will only show 10:5 ,

相关标签:
5条回答
  • 2020-12-31 17:50

    I tried this way. It's not brief but it works.

    var dt = new Date();
    if (parseInt(dt.getMinutes()) < 10) {minutes = "0" + dt.getMinutes();} else minutes = dt.getMinutes();
    if (parseInt(dt.getSeconds()) < 10) {seconds = "0" + dt.getSeconds();} else seconds = dt.getSeconds();
    
    var time = dt.getHours() + ":" + minutes + ":" + seconds;
    document.write("Now is:" + time);
    
    //Result: Now is: 22:47:00
    

    I hope it will be useful

    0 讨论(0)
  • 2020-12-31 18:00

    Since you're likely to run into presentational issues in the future along the same lines, I'd recommend picking a favorite string formatting function for Javascript.

    Some examples:

    • http://www.masterdata.se/r/string_format_for_javascript/
    • http://www.diveintojavascript.com/projects/javascript-sprintf

    Then you can do something like "{0:00}:{1:00}".format(current.getHours(), current.getMinutes()) or even better,

    var d = new Date();
    var s = d.format("hh:mm:ss tt");
    // Result: "02:28:06 PM"
    
    0 讨论(0)
  • 2020-12-31 18:01

    I like this way of doing things... Javascript add leading zeroes to date

    const d = new Date();
    const date = (`0${d.getMinutes()}`).slice(-2);
    console.log(date); // 09;
    

    2019 Update: But I now prefer

    const d = new Date();
    const date = String(d.getMinutes()).padStart(2, '0');
    console.log(date); // 09;
    
    0 讨论(0)
  • 2020-12-31 18:06

    You can just grab the first 5 characters of the time string.

    (new Date()).toTimeString().substr(0,5)
    
    0 讨论(0)
  • 2020-12-31 18:08

    And what is your issue?

    var minutes = (current.getMinutes() < 10? '0' : '') + current.getMinutes();
    

    Since you'll have the same problem with hours, wrap it in a small utility function:

    function pad(var value) {
        if(value < 10) {
            return '0' + value;
        } else {
            return value;
        }
    }
    

    And later simply:

    pad(current.getHours()) + ":" + pad(current.getMinutes())
    
    0 讨论(0)
提交回复
热议问题