Number of seconds to ISO format

JavaScript, Date, Math, String · Oct 13, 2021

Returns the ISO format of the given number of seconds.

const formatSeconds = s => {
  const [hour, minute, second, sign] =
    s > 0
      ? [s / 3600, (s / 60) % 60, s % 60, '']
      : [-s / 3600, (-s / 60) % 60, -s % 60, '-'];

  return (
    sign +
    [hour, minute, second]
      .map(v => `${Math.floor(v)}`.padStart(2, '0'))
      .join(':')
  );
};
formatSeconds(200); // '00:03:20'
formatSeconds(-200); // '-00:03:20'
formatSeconds(99999); // '27:46:39'

More like this

  • Format duration

    Returns the human-readable format of the given number of milliseconds.

    JavaScript, Date · Oct 22, 2020

  • Date to ISO format with timezone

    Converts a date to extended ISO format (ISO 8601), including timezone offset.

    JavaScript, Date · Oct 13, 2021

  • String is ISO formatted date

    Checks if the given string is valid in the simplified extended ISO format (ISO 8601).

    JavaScript, Date · Nov 29, 2020