Human-Readable Duration Formatting

Convert milliseconds into compact durations such as 1h 5m 20s with unit limits, short labels and zero handling.

JavascriptData Integrity

Code

javascriptsnippet
41 lines
const UNITS = [
  ["day", 86400000],
  ["hour", 3600000],
  ["minute", 60000],
  ["second", 1000],
];

// Human-readable duration formatting for elapsed time.
export function formatDuration(milliseconds, options = {}) {
  if (typeof milliseconds !== "number" || !Number.isFinite(milliseconds) || milliseconds < 0) {
    throw new RangeError("duration must be a non-negative finite number");
  }
  const { maxUnits = UNITS.length, separator = " ", short = false } = options;
  if (!Number.isInteger(maxUnits) || maxUnits < 1) {
    throw new RangeError("maxUnits must be a positive integer");
  }
  let remaining = Math.floor(milliseconds);
  const parts = [];
  for (const [name, size] of UNITS) {
    if (parts.length >= maxUnits) break;
    const amount = Math.floor(remaining / size);
    remaining -= amount * size;
    if (amount === 0 && parts.length === 0) continue;
    if (amount === 0) continue;
    const label = short ? name[0] : " " + name + (amount === 1 ? "" : "s");
    parts.push(amount + label);
  }
  if (parts.length === 0) return short ? "0s" : "0 seconds";
  return parts.join(separator);
}

export function formatDurationClock(milliseconds) {
  if (typeof milliseconds !== "number" || !Number.isFinite(milliseconds) || milliseconds < 0) {
    throw new RangeError("duration must be a non-negative finite number");
  }
  const totalSeconds = Math.floor(milliseconds / 1000);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  return [hours, minutes, seconds].map((part) => String(part).padStart(2, "0")).join(":");
}

How it works

Human-Readable Duration Formatting reduces to the functions formatDuration and formatDurationClock.

Iteration happens inside for (const [name, size] of UNITS) — everything outside it runs once. Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.

The result is a fresh construction, so callers can keep their originals.

What to watch for

  • The guard parts.length >= maxUnits short-circuits the flow with an early break when its condition holds.

Putting it to use

The primary signature is export function formatDuration(milliseconds, options = {})

Callers only need formatDuration — everything else stays internal.

Core lines

return [hours, minutes, seconds].map((part) => String(part).padStart(2, "0")).join(":");
throw new RangeError("duration must be a non-negative finite number");
throw new RangeError("maxUnits must be a positive integer");

Interactive Tools for This Topic

FAQ

Does `formatDuration` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
What happens if the preconditions do not hold?
`RangeError` is raised at the guard (`parts.length >= maxUnits`), so invalid state never reaches the main logic.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `formatDuration`, `formatDurationClock` at load time.