javascriptreal-time-clock

How do I add zeros before hours/minute/seconds when they are < 10 in Javascript?


I encountered a problem while trying to create a real-time-clock: I'm trying to show a zero before the number that represents minutes/hours/seconds when they are < 10, but the function doesn't work. May someone explain where I'm wrong and why please? Is it the poisition of the if statement or what? What does i represents?

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>
  <p id="p"></p>
  <script>
    function startClock() {

      var currentDate = new Date();

      var time = currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds();

      document.getElementById("p").innerHTML = time;

      setTimeout(startClock, 1000);
    }

    function zeros(i) {
      if (i < 10) {
        return "0" + i;
      } else {
        return i;
      }
    }
    startClock();
    zeros();
  </script>
</body>

</html>


Solution

  • Your zeros function takes a number and add a zero in front if the number is < 10.

    You need to call your zeros function when you set the time to convert hours, minutes, and seconds to zero-added form.

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title></title>
    </head>
    
    <body>
      <p id="p"></p>
      <script>
        function startClock() {
    
          var currentDate = new Date();
    
          var time = zeros(currentDate.getHours()) + ":" + zeros(currentDate.getMinutes()) + ":" + zeros(currentDate.getSeconds());
    
          document.getElementById("p").innerHTML = time;
    
          setTimeout(startClock, 1000);
        }
    
        function zeros(i) {
          if (i < 10) {
            return "0" + i;
          } else {
            return i;
          }
        }
        startClock();
        zeros(); // this doesn't do anything????
      </script>
    </body>
    
    </html>