Home > Software engineering >  Why does EST JavaScript Date sets 12:00:00AM to 0:00:00 AM?
Why does EST JavaScript Date sets 12:00:00AM to 0:00:00 AM?

Time:09-06

my JavaScript display time function works fine, but once it hits 12:00:00 AM EST, it changes to 0:00:00 AM. Essentially, I want it to show as 12:00:00 AM when the clock strikes midnight. I have included my code below so anyone can help? Thank you!

let session = document.getElementById("session");

if (session) {
  displayTime();
  setInterval(displayTime, 1000);
  clearInterval(displayTime);
}

function displayTime() {
  let dateTime = new Date();
  let hrs = dateTime.getHours();
  let mins = dateTime.getMinutes();
  let sec = dateTime.getSeconds();

  if (hrs > 12) {
    session.innerHTML = "\xa0"   "PM";
  } else {
    session.innerHTML = "\xa0"   "AM";
  }

  if (hrs > 12) {
    hrs = hrs - 12;
  } 
  

  if (mins < 10) {
    mins = "0"   mins;
  }

  if (sec < 10) {
    sec = "0"   sec;
  }

  document.getElementById("hours").innerHTML = hrs;
  document.getElementById("minutes").innerHTML = mins;
  document.getElementById("seconds").innerHTML = sec;
}

CodePudding user response:

There are two things to change.

  • The condition to display "PM" should be >= 12 instead of > 12

  • The mapping of 24-hours to 12-hours should never leave 0 as-is. You can use the remainder operator.

Here are the corrected relevant lines:

  if (hrs >= 12) {
    session.innerHTML = "\xa0"   "PM";
  } else {
    session.innerHTML = "\xa0"   "AM";
  }

  hrs = (hrs   11) % 12   1;

Alternative

To format a time, look at toLocaleTimeString with its options:

dateTime.toLocaleTimeString("en-US")

If you really need to chop the date parts into different elements on your HTML document, then:

function displayTime() {
  let dateTime = new Date();
  let [hrs, mins, sec, apm] = dateTime.toLocaleTimeString("en-US").split(/\W/);
  console.log(hrs, mins, sec, apm);
  document.getElementById("hours").textContent = hrs;
  document.getElementById("minutes").textContent = mins;
  document.getElementById("seconds").textContent = sec;
  document.getElementById("session").textContent = "\xa0"   apm;
}

Remarks

Unrelated, but clearInterval is called at the wrong time and with the wrong argument, which luckily makes it ineffective, or your timer wouldn't tick at all.

clearInterval should get as argument a value that was returned by a previous call to setInterval.

In your code clearInterval is executed immediately after setInterval, which makes little sense. You should call it conditionally in the callback that is passed to setInterval. Maybe when a certain time has passed...

  • Related