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>