displayTime method

  1. @useResult
String displayTime({
  1. bool showHours = true,
})

Formats this duration as a zero-padded stopwatch clock string.

  • When showHours is true (default): 'HH:MM:SS.mmm'.
  • When showHours is false: 'MM:SS.mmm'.

Hours are NEVER reduced modulo 24 — a duration longer than a day shows the full hour count (Duration(hours: 25) -> '25:00:00.000'). This is the intended difference from the day-aware top-level formatDuration, and makes the output correct for elapsed timers that exceed 24 hours. padLeft(2) is a minimum width, not a truncation, so triple-digit hours (Duration(hours: 100)) render in full as '100:00:00.000'.

Microseconds are intentionally dropped: only whole-millisecond precision is shown, so Duration(microseconds: 500) yields '...00:00.000'.

Negative durations are NOT special-cased. Because Dart's % returns a non-negative result for a positive divisor, the minute/second/millisecond components wrap rather than show a - sign (e.g. Duration(seconds: -5) -> '00:00:55.000', since -5 % 60 == 55). Callers that need a signed clock should reverse first and prefix the sign themselves.

Example:

Duration(hours: 1, minutes: 30, seconds: 45, milliseconds: 123)
    .displayTime(); // '01:30:45.123'
Duration(minutes: 5, seconds: 30, milliseconds: 50)
    .displayTime(showHours: false); // '05:30.050'

Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String displayTime({bool showHours = true}) {
  // Hours are unbounded (no mod-24) so timers past a day stay correct.
  final String hoursStr = showHours ? '${inHours.toString().padLeft(2, '0')}:' : '';
  final String minutesStr = '${(inMinutes % 60).toString().padLeft(2, '0')}:';
  final String secondsStr = (inSeconds % 60).toString().padLeft(2, '0');

  // Millisecond fraction only; microseconds are deliberately not surfaced.
  final String millisecondsStr = '.${(inMilliseconds % 1000).toString().padLeft(3, '0')}';

  return '$hoursStr$minutesStr$secondsStr$millisecondsStr';
}