Coding Challenge - #6: Format Elapsed Time

Write a function formatDuration(seconds) that converts a non-negative integer of seconds into a "MM:SS" or "HH:MM:SS" string. Omit the hours portion if the duration is under one hour, and ensure all parts are zero-padded to two digits (for example, 65 becomes "01:05" and 3661 becomes "01:01:01").

function formatDuration(seconds) {
  // Your code here
}

Rules:

  • Assume seconds is always an integer >= 0
  • Single-digit values must be zero-padded (e.g. 5 seconds → “00:05”)
  • Return “HH:MM:SS” only when seconds >= 3600, otherwise return “MM:SS”

Post your solution as a reply. Answer goes up in about a day.

padStart is definitely the move here, saves so much boilerplate. I always forget about it until I’m halfway through writing an if (num < 10) check.

function formatDuration(seconds) {
  const pad = (num) => String(num).padStart(2, '0');

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  if (seconds >= 3600) {
    return `${pad(hours)}:${pad(minutes)}:${pad(remainingSeconds)}`;
  } else {
    return `${pad(minutes)}:${pad(remainingSeconds)}`;
  }
}

Challenge solution: The solution converts total seconds into hours, minutes, and seconds, then formats these components with zero-padding based on the total duration.

One way to do it:

function formatDuration(seconds) {
  const pad = (num) => num.toString().padStart(2, '0');

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;

  if (seconds >= 3600) {
    return `${pad(hours)}:${pad(minutes)}:${pad(remainingSeconds)}`;
  } else {
    return `${pad(minutes)}:${pad(remainingSeconds)}`;
  }
}

Why:
This function first defines a helper pad function to ensure two-digit zero-padding for any number. It then calculates hours, minutes, and remaining seconds using integer division and modulo operations. Finally, it conditionally formats the output string to ‘HH:MM:SS’ if the total seconds are 3600 or more, otherwise it returns ‘MM:SS’, ensuring all parts are correctly padded.

First-answer leaderboard

  1. @kirupa - 4 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @emmawalter5 - 1 (first)