Search code examples
javascripttimelivesecondsreal-time-clock

Removing seconds from Live clock using JavaScript


I was wondering if it is possible to remove the seconds group in a live clock made with JavaScript. Ive been tinkering with it for a while now and have not been successful so far. Any advice or guidance well be gratefully welcomed.

Here's what I'm working with...

function myClock() {
  setTimeout(function() {
    const date = new Date();
    const timeOutput = date.toLocaleTimeString();
    document.getElementById("demo").innerHTML = timeOutput;
    myClock();
  }, 1000)
}
myClock();
<div id="demo"></div>


Solution

  • You could just split your timeOutput and then grab the hour and minutes, like so:

    function myClock() {         
        setTimeout(function() {   
          const date = new Date();
          const dateString = date.toLocaleTimeString('en-GB', {hour12: false});
          const split = dateString.split(":");
          const hour = parseInt(split[0]);
          const min = parseInt(split[1]);
          const period = hour < 12 ? 'AM' : 'PM';
          const timeOutput = hour + ':' + min + ' ' + period;
          document.getElementById("demo").innerHTML = timeOutput; 
          myClock();
        }, 1000)
    }
      
    myClock();
    <div id="demo"></div>