DEV Community

Alex Parra
Alex Parra

Posted on

JavaScript - Seconds to HH:MM:SS

Yesterday, while making a game where I wanted to show the time elapsed since the game started I put together this short helper:

const SECONDS_PER_DAY = 86400;
const HOURS_PER_DAY = 24;

/**
 * Convert seconds to HH:MM:SS
 * If seconds exceeds 24 hours, hours will be greater than 24 (30:05:10)
 *
 * @param {number} seconds
 * @returns {string}
 */
const secondsToHms = (seconds: number): string => {
  const days = Math.floor(seconds / SECONDS_PER_DAY);
  const remainderSeconds = seconds % SECONDS_PER_DAY;
  const hms = new Date(remainderSeconds * 1000).toISOString().substring(11, 19);
  return hms.replace(/^(\d+)/, h => `${Number(h) + days * HOURS_PER_DAY}`.padStart(2, '0'));
};
Enter fullscreen mode Exit fullscreen mode

The above converts seconds 1234 to 00:20:34.

  secondsToHms(1234); // '00:20:34'
Enter fullscreen mode Exit fullscreen mode

The first version I wrote didn't handle the case of seconds being over 24 hours.
Not really needed in the situation at hand but for the sake of completeness I opted to handle it, especially because the various existing examples I've found don't deal with the day overflow and that's why I decided to share this.

Interactive and tested at CodeSandbox
https://codesandbox.io/embed/js-seconds-to-hhmmss-32zo4?fontsize=14&hidenavigation=1&module=%2Findex.ts&previewwindow=tests&theme=dark

Hope it's useful to you. Cheers.

PS: In case you prefer plain JavaScript...

const SECONDS_PER_DAY = 86400;
const HOURS_PER_DAY = 24;

/**
 * Convert seconds to HH:MM:SS
 * If seconds exceeds 24 hours, hours will be greater than 24 (30:05:10)
 *
 * @param {number} seconds
 * @returns {string}
 */
const secondsToHms = seconds => {
  const days = Math.floor(seconds / SECONDS_PER_DAY);
  const remainderSeconds = seconds % SECONDS_PER_DAY;
  const hms = new Date(remainderSeconds * 1000).toISOString().substring(11, 19);
  return hms.replace(/^(\d+)/, h => `${Number(h) + days * HOURS_PER_DAY}`.padStart(2, '0'));
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)