0

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>
Spectric
  • 30,714
  • 6
  • 20
  • 43
Alex
  • 29
  • 6
  • Just replace the setTimeout delay of 1 second (`}, 1000)`) by a delay of a minute should work: (`}, 60 * 1000)`) – Louys Patrice Bessette Jan 16 '22 at 21:05
  • 1
    Does this answer your question? [How to get LocaleTime without seconds in javascript?](https://stackoverflow.com/questions/21298035/how-to-get-localetime-without-seconds-in-javascript) – prettyInPink Jan 16 '22 at 21:07

1 Answers1

0

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>
Ryan Walls
  • 191
  • 1
  • 13
  • Thanks @Ryan. Your solution somehow strips out the AM and PM unit. Anyway on bringing that back? – Alex Jan 17 '22 at 18:47
  • I have updated my answer to include AM/PM. It just runs a check on the hour to see if it's less than 12. If it is, set to AM, otherwise set to PM. ```const period = hour < 12 ? 'AM' : 'PM';``` – Ryan Walls Jan 17 '22 at 19:32
  • Working perfectly :) – Alex Jan 17 '22 at 19:38