How to Format a Duration as a HH:MM:SS String

Last reviewed in September 2019 by Frank Treacy

Photo by Aron Visuals on Unsplash

The shortest, most elegant and reliable way to get HH:mm:ss from a Duration is doing:

format(Duration d) => d.toString().split('.').first.padLeft(8, "0");

Example usage:

main() {
  final d1 = Duration(hours: 17, minutes: 3);
  final d2 = Duration(hours: 9, minutes: 2, seconds: 26);
  final d3 = Duration(milliseconds: 0);
  print(format(d1)); // 17:03:00
  print(format(d2)); // 09:02:26
  print(format(d3)); // 00:00:00

If we are dealing with smaller durations and needed only minutes and seconds:

format(Duration d) => d.toString().substring(2, 7);

Did this work for you? Let us know in the comments!

The best from the Flutter-verse in 3 minutes or less? Join Snacks!

Delivered twice monthly. No link walls. No spam. EVER.