This tutorial shows you how to format a Duration
object in Dart to HH:mm:ss format.
Dart's Duration
is commonly used to store a duration value as it can be easily converted to various time units. However, in some cases, it's necessary to format the duration into a more readable time, such as in HH:mm:ss
format.
As for now, the Duration
class doesn't have such a method. However, the computation is quite easy. Below is the explanation of how to do it.
Convert Duration to HH:mm:ss
Format
Let's say we have a variable named duration
whose type is Duration
. First, to get the hours, you can directly obtain it from the inHours
property.
final HH = duration.inHours
The returned value is an integer. In HH:mm:ss
format, usually each part should have not less than two digits. Since the length of the integer can be less than two digits, we need to pad the value to be at least two digit lengths.
final HH = (duration.inHours).toString().padLeft(2, '0');
For the minutes part, you need to get the remainder that's already included in hours. Since an hour is 60 minutes, the value for minutes is the remainder of inMinutes
property divided by 60. Then, we need to pad the value to have at least two digits.
final mm = (duration.inMinutes % 60).toString().padLeft(2, '0');
For the seconds part, you need to get the remainder that's already included in hours and minutes. The computation is similar to the minutes part, but what you need to get is the remainder of inSeconds
property divided by 60 (because a minute is 60 seconds).
final ss = (duration.inSeconds % 60).toString().padLeft(2, '0');
Based on the computation above, we can write a function as follow.
String formatDurationInHhMmSs(Duration duration) {
final HH = (duration.inHours).toString().padLeft(2, '0');
final mm = (duration.inMinutes % 60).toString().padLeft(2, '0');
final ss = (duration.inSeconds % 60).toString().padLeft(2, '0');
return '$HH:$mm:$ss';
}
Below are the examples that use the function above along with the results.
print(formatDurationInHhMmSs(Duration(seconds: 1))); // 00:00:01
print(formatDurationInHhMmSs(Duration(seconds: 100))); // 00:01:40
print(formatDurationInHhMmSs(Duration(seconds: 86400))); // 24:00:00
print(formatDurationInHhMmSs(Duration(seconds: 86405))); // 24:00:05
print(formatDurationInHhMmSs(Duration(seconds: 86465))); // 24:01:05
Summary
That's how to convert a Duration
object into a String
in HH:mm:ss
in Dart, which also works in any Dart framework including Flutter. If you need to use another format, for example including the days or excluding the hours, you should be able to do it with the similar computation logic. The first part can be obtained directly from a property of the Duration
object, unless the time unit is greater than days. The next parts are the remainder that's not included in the previous parts.
You can also read about: