2

I asked about a day ago how to make a clock. The code I'm using works, but instead of going from 18:59:59 to 19:00:00, it goes from 18:59:59 to 19:0:0. How would I add a zero upfront if something is a single digit, so instead of 19:0:0, it becomes 19:00:00? Here is the code I'm using.

setInterval(function(){
    let i = 5;
    const timer = setInterval(() => {
        var date = new Date();
        var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
        document.getElementById('clock').innerHTML = time;

        i--;
        if (i < 0) {
            clearInterval(timer)
        }
    }, 1000);
});
<p id="clock"></p>

Thanks!

turivishal
  • 34,368
  • 7
  • 36
  • 59
Westlenando
  • 88
  • 1
  • 8
  • 1
    Does this answer your question? [getMinutes() 0-9 - How to display two digit numbers?](https://stackoverflow.com/questions/8935414/getminutes-0-9-how-to-display-two-digit-numbers) – Kundan Jun 20 '20 at 14:33

1 Answers1

0

Try this:

setInterval(function(){
    let i = 5;
    const timer = setInterval(() => {
        var date = new Date();
        var time = ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2)
        document.getElementById('clock').innerHTML = time;

        i--;
        if (i < 0) {
            clearInterval(timer)
        }
    }, 1000);
});
<p id="clock"></p>
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • Alternatively, use `padStart` which exists for exactly this purpose: `var time = [date.getHours(), date.getMinutes(), date.getSeconds()].map(v => v.toString().padStart(2, '0')).join(':')` – CherryDT Jun 20 '20 at 14:39