0

I am building a clock that updates every second using setInterval and new Date(). But, I am having trouble changing one digit numbers to two digit numbers using and array. For example, I want 5 hours, 9 minutes, and 5 seconds to display as 05:09:05 (adding zeros to the front of one digit numbers). For some odd reason, my array with a for loop and if statement doesn't do this. Here's my code:

$(document).ready(function () {
  /* Variables */
  var d;
  var h;
  var m;
  var s;
  var arr;
  
  setInterval(function(){
    /* Get time every second */
    d = new Date();
    h = d.getHours();
    m = d.getMinutes();
    s = d.getSeconds();
    
    /* Check for character count */
    arr = [h, m, s];
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].toString().length == 1) {
        arr[i] = '0' + arr[i];
      }
    }
    
    $('h1').html(h + ':' + m + ':' + s)
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>12:00:00</h1>

2 Answers 2

4

You forgot to output the array instead of the individual h, m, s.

$(document).ready(function () {
  /* Variables */
  var d;
  var h;
  var m;
  var s;
  var arr;
  
  setInterval(function(){
    /* Get time every second */
    d = new Date();
    h = d.getHours();
    m = d.getMinutes();
    s = d.getSeconds();
    
    /* Check for character count */
    arr = [h, m, s];
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].toString().length == 1) {
        arr[i] = '0' + arr[i];
      }
    }
    
    //$('h1').html(arr[0] + ':' + arr[1] + ':' + arr[2])
    $('h1').html(arr.join(':')) // join instead of outputting individually
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>12:00:00</h1>

Sign up to request clarification or add additional context in comments.

Comments

0

When you put the strings in the array, it doesn't directly put the object, it puts a copy of the object.

Then when it is displayed, instead of using directly h, m and s (the original objects that have not been modified) it displays the items from the array (arr[0], ...).

I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.