Skip to content

formatDuration()

formatDuration(duration, options?): string

Defined in: utils/date/formatDuration.ts:238

Format a time duration (e.g. milliseconds or seconds) into a human-readable string.

The function is intentionally flexible and dependency-free:

  • Supports input in "milliseconds" or "seconds".
  • Configurable minimum / maximum units (minUnit, maxUnit).
  • Can show all units ("1 hour 30 minutes") or only the largest unit ("1 hour").
  • Allows zero-valued units when desired (includeZeroUnits).
  • Supports label overrides and even full unit formatting via formatUnit.
  • Optional sign control for negative durations.

Parameters

duration

number

The duration value, interpreted according to options.inputUnit (default "milliseconds").

options?

FormatDurationOptions = {}

Additional formatting configuration.

Returns

string

A human-readable representation of the duration, such as:

  • "42 seconds"
  • "1 minute 30 seconds"
  • "2 hours"
  • "1h 5m" (with appropriate formatUnit overrides)

Throws

When duration is not a finite number.

Examples

ts
formatDuration(90_000); // "1 minute 30 seconds"
formatDuration(5_000, { inputUnit: 'seconds' }); // "1 hour 23 minutes 20 seconds"
ts
// Only show the largest unit:
formatDuration(90_000, { largestUnitOnly: true }); // "1 minute"
ts
// Use abbreviated labels:
formatDuration(90_000, {
  labels: {
    minute: 'min',
    minutePlural: 'min',
    second: 's',
    secondPlural: 's',
  },
});
// → "1 min 30 s"
ts
// Fully custom unit formatting:
formatDuration(90_000, {
  formatUnit: (unit, value) => {
    const short = { hour: 'h', minute: 'm', second: 's' } as const;
    return `${value}${short[unit] ?? unit}`;
  },
});
// → "1m 30s"

Released under the MIT License.