formatDuration function

String formatDuration(
  1. Duration d, {
  2. bool isShort = true,
  3. bool isIncludeSeconds = true,
  4. bool isIncludeMilliseconds = false,
})

Formats Duration as a short string (e.g. "2h 30m" or "1d 2h").

isIncludeSeconds and isIncludeMilliseconds add smaller units when non-zero.

A negative duration formats its magnitude with a leading minus (-90 min -> -1h 30m). When nothing non-zero is shown (e.g. -500 ms without milliseconds) the zero label is returned unsigned. The one unsupported input is the most negative Duration, whose magnitude overflows.

Sub-second durations: the zero label (0s / 0 seconds) appears only when no unit is shown, so 500 ms with isIncludeMilliseconds is 500ms (-500ms when negative), never 0s 500ms. Sub-millisecond remainders are dropped, so -500 µs formats as the unsigned 0s. Audited: 2026-06-12 11:26 EDT

Implementation

String formatDuration(
  Duration d, {
  bool isShort = true,
  bool isIncludeSeconds = true,
  bool isIncludeMilliseconds = false,
}) {
  // Bug fix: Dart's % is always non-negative, so a negative duration wrapped
  // (-90 min printed as '23h 30m'). Format the magnitude, then add the sign.
  final _FormatOptions options = (
    isShort: isShort,
    isIncludeSeconds: isIncludeSeconds,
    isIncludeMilliseconds: isIncludeMilliseconds,
  );
  final String text = _formatMagnitude(d.abs(), options);
  // No sign on the zero labels: "-0s" would claim a negative amount was shown.
  if (!d.isNegative || text == _kZeroS || text == _kZeroSeconds) {
    return text;
  }
  return '-$text';
}