Home > Mobile >  Remove seconds from a clock
Remove seconds from a clock

Time:08-18

I have been trying to do some research on how to do this but still no luck. Basically, I have a clock on a 12 hour format that shows automatically on page load. What I'm trying to do here is that how will I be able to change the clock format to 24 hour by using an AddEventLister? Would also like to add another AddEventListener that removes the seconds from it. Here's my code

function myClock() {
  let date = new Date(); 
  let hh = date.getHours();
  let mm = date.getMinutes();
  let ss = date.getSeconds();
  let session = "AM";

  if(hh == 0){
      hh = 12;
  }
  if(hh > 12){
      hh = hh - 12;
      session = "PM";
   }

   hh = (hh < 10) ? "0"   hh : hh;
   mm = (mm < 10) ? "0"   mm : mm;
   ss = (ss < 10) ? "0"   ss : ss;
   
   let time = hh   ":"   mm   ":"   ss   " "   session;

  document.getElementById("time-now").innerText = time; 
  var t = setTimeout(function(){myClock()}, 1000); 
 
}
myClock();
<span id="time-now"></span>

CodePudding user response:

Here's the logic compressed (and edge-case tested) using .toLocaleTimeString(). With it, you can specify a locale and several formatting options, including 24-hour clock....

function myClock(locale) {
  const date = new Date(); 
  const time = date.toLocaleTimeString(locale, { hour12: false })
  document.getElementById("time-now").innerText = time; 
  setTimeout(() => myClock(locale), 1000); 
}
// US just for example
myClock('en-US');
<span id="time-now"></span>

CodePudding user response:

const  myClock=(locale)=> {
  const date = new Date(); 
  const time = date.toLocaleTimeString(locale, { hour12: false 
   })
  document.getElementById("time-now").innerText = time; 
  setTimeout(() => myClock(locale), 1000); 
}
// US just for example
myClock('en-US');
  • Related