Skip to content Skip to sidebar Skip to footer

Clock And Date Javascript

Im creating a JS clock/date. I previously got the time to work perfectly then I decided to add more onto my clock (date). Right now I cant figure why it isn't working. If anyone co

Solution 1:

Your code works, it is just not visible because you do not have seconds showing

Also change

setTimeout("timedate()", 1000); 

to

setTimeout(timedate, 1000); 

because it is not recommended

and remove the <--

Make sure it runs onload or after the tag you want to show it in

Alternatively remove the line and change

timedate();

to

setInterval(timedate,1000)

const pad = num => ("0" + num).slice(-2);
const timedate = () => {
  const currentTime = new Date();
  let hours = currentTime.getHours();
  const minutes = pad(currentTime.getMinutes());
  const seconds = pad(currentTime.getSeconds());

  const d = currentTime.getDate();
  const day = pad(d);
  const month = pad(currentTime.getMonth() + 1);
  const yy = currentTime.getFullYear();

  let dn = "PM"
  if (hours <= 12) dn = "AM";
  if (hours >= 12) hours -= 12;
  if (hours == 0) hours = 12;
  hours = pad(hours);
  document.getElementById('timedate').innerHTML = "" +
    hours + ":" +
    minutes + ":" +
    seconds + dn + " " +
    day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
  setInterval(timedate, 1000);
});
<span id="timedate"></span>

Solution 2:

If you set the timeout with setTimeout(timedate, 1000) instead of your current magic string version, it works.



Post a Comment for "Clock And Date Javascript"