getElapsedStr static method

String getElapsedStr(
  1. Duration duration, {
  2. bool showMilliSeconds = false,
})

Converts a Duration to a human-readable elapsed time string.

Parameters:

  • duration: The duration to format
  • showMilliSeconds: Whether to include milliseconds. Defaults to false

Returns formatted string like "2d 3hr 15m 30s" or "0s" if duration is zero.

Implementation

static String getElapsedStr(Duration duration,
    {bool showMilliSeconds = false}) {
  int d = duration.inMilliseconds ~/ Duration.millisecondsPerDay;

  int rem = duration.inMilliseconds - (d * Duration.millisecondsPerDay);

  int h = rem ~/ Duration.millisecondsPerHour;

  rem = rem - (h * Duration.millisecondsPerHour);

  int m = rem ~/ Duration.millisecondsPerMinute;

  rem = rem - (m * Duration.millisecondsPerMinute);

  int s = rem ~/ Duration.millisecondsPerSecond;

  rem = rem - (s * Duration.millisecondsPerSecond);

  int ms = rem;

  List<String> res = [];

  if (d > 0) {
    res.add('${d}d');
  }

  if (h > 0) {
    res.add('${h}hr');
  }

  if (m > 0) {
    res.add('${m}m');
  }

  if (s > 0) {
    res.add('${s}s');
  }

  if (showMilliSeconds) {
    if (ms > 0) {
      res.add('${ms}ms');
    }
  }

  return res.isNotEmpty ? res.join(' ') : '0s';
}