Formatting a Duration like HH:mm:ss

Question

Asked by Jonas on February 19, 2019 (source).

Is there a good way to format a Duration in something like hh:mm:ss, without having to deal with time zones?

I tried this:

DateTime durationDate = DateTime.fromMillisecondsSinceEpoch(0);
String duration = DateFormat('hh:mm:ss').format(durationDate);

But I always get 1 hour to much, in this case it would say 01:00:00

And When I do this:

Duration(milliseconds: 0).toString();

I get this: 0:00:00.000000

Answer

Question answered by diegoveloper (source).

You can use Duration and implement this method:

String _printDuration(Duration duration) {
  String twoDigits(int n) => n.toString().padLeft(2, "0");
  String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
  String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
  return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
}

Usage:

final now = Duration(seconds: 30);
print("${_printDuration(now)}");
DART FLUTTER
SHARE: