Alex204 Alex204 - 21 days ago 8
Javascript Question

Creating a date and time function that updates every second

So I need this function to update every second with the current date and time. Also if minute or second is less than 10 I need to add a 0 in front. Heres my code, not sure what I'm doing wrong, I feel pretty confident in my code. Any suggestions?

<script>
"use strict"
// updates digital clock every second
var tick = setInterval(digitalClock, 1000);
//digital clock function
function digitalClock() {
var currentTime();
var dateObject = new Date();
var hour = dateObject.getHours();
var minute = dateObject.getMinutes();
var second = dateObject.getSeconds();
if (minute < 0) {
minute = "0" + minute;
}
if (second < 0) {
second = "0" + second;
}
currentTime = hour + ":" + minute + ":" + second;
document.getElementById('time').innerHTML = currentTime;
}
</script>


I was told that innerHTML wont work where I put it, but I dont see why not

Answer

Remove () after the currentTime and also you need to check if minute and second is less than 10, not 0

<p id='time'></p>

<script>
  function digitalClock() {
  var dateObject = new Date();
  var parts = {
    hours: dateObject.getHours(),
    minutes: dateObject.getMinutes(),
    seconds: dateObject.getSeconds(),
    month: dateObject.getUTCMonth() + 1,// +1 because the month starts from 0
    day: dateObject.getUTCDate(),
    year: dateObject.getUTCFullYear()
  };
 
  if (parts.minutes < 10) {
     parts.minutes = "0" + parts.minutes;
  }
  if (parts.seconds < 10) {
     parts.seconds = "0" + parts.seconds;
  }
    
  document.getElementById('time').innerHTML = `${parts.month}/${parts.day}/${parts.year} ${parts.hours}:${ parts.minutes}:${parts.seconds}`;  
}

var tick = setInterval(digitalClock, 1000);
  </script>

UPDATED

This is by pure JavaScript. But I advice you to use momentJs if you need to work with the times and dates many times