How do I show the current time in the format HH:MM:SS?
Advertisement
Answer
function checkTime(i) { if (i < 10) { i = "0" + i; } return i; } function startTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); // add a zero in front of numbers<10 m = checkTime(m); s = checkTime(s); document.getElementById('time').innerHTML = h + ":" + m + ":" + s; t = setTimeout(function() { startTime() }, 500); } startTime();
<div id="time"></div>
DEMO using javaScript only
Update
(function () { function checkTime(i) { return (i < 10) ? "0" + i : i; } function startTime() { var today = new Date(), h = checkTime(today.getHours()), m = checkTime(today.getMinutes()), s = checkTime(today.getSeconds()); document.getElementById('time').innerHTML = h + ":" + m + ":" + s; t = setTimeout(function () { startTime() }, 500); } startTime(); })();