Human-Readable Duration Formatting
Convert milliseconds into compact durations such as 1h 5m 20s with unit limits, short labels and zero handling.
Code
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 >= maxUnitsshort-circuits the flow with an earlybreakwhen 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
Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.