Home > Back-end >  Showing complete 24hr time display (00:00:00)
Showing complete 24hr time display (00:00:00)

Time:01-31

I have a basic script to display PST time based on 24:00hr UTC clock. Everything is working fine except it only displays 0:00:00 (h:m:s) for hours 0-9am and I want to have an extra 0 as a prefix (ex: 00:00:00).

My script is:

function startTime() {
  const today = new Date();
  let h = today.getUTCHours()-8;
  let m = today.getUTCMinutes();
  let s = today.getUTCSeconds();
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('txt').innerHTML =  h   ":"   m   ":"   s;
  setTimeout(startTime, 1000);
}

I tried adding the following with no such luck:

function checkTime(h) {
  if (h < 10) {h = "0"   h};  // add zero in front of numbers < 10
  return h;
}

CodePudding user response:

Note that the en-GB locale displays half-past midnight as 00:30:00, but the en-US locale displays it as 24:30:00.

const today = new Date();
const time = today.toLocaleTimeString('en-GB', 
  {timeZone: 'America/Los_Angeles', hour12: false})
console.log(time)

CodePudding user response:

Maybe you forgot to call h = checkTime(h);

function startTime() {
  const today = new Date();
  let h = today.getUTCHours()-8;
  let m = today.getUTCMinutes();
  let s = today.getUTCSeconds();
  h = checkTime(h);
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('txt').innerHTML =  h   ":"   m   ":"   s;
  setTimeout(startTime, 1000);
}

function checkTime(h) {
  if (h < 10) {h = "0"   h};  // add zero in front of numbers < 10
  return h;
}
startTime();
<div id="txt"></div>

  • Related