For example, if times is given as 1.05 seconds, we need to convert it as 00:01:05.
How can we achieve this in Flutter?
Also, if a time is given as duration in milliseconds, how do we convert it to the 00:00:00 format?
CodePudding user response:
You just need some simple integer maths to separate the duration into the units you want and some string formatting to make sure that single-digit numbers get leading zeros.
String formatForVideo(Duration d) {
final millis = d.inMilliseconds;
if (millis >= 3600000) {
throw FormatException('too big to format');
}
final minutes = _pad2(d.inMinutes);
final seconds = _pad2(d.inSeconds % 60);
final cents = _pad2((millis % 1000) ~/ 10);
return '$minutes:$seconds.$cents';
}
String _pad2(int i) => i.toString().padLeft(2, '0');
Which gives expected results:
print(formatForVideo(Duration(minutes: 0, seconds: 1, milliseconds: 50))); // 00:01.05
print(formatForVideo(Duration(minutes: 9, seconds: 51, milliseconds: 50))); // 09:51.05
print(formatForVideo(Duration(minutes:60))); // exception
CodePudding user response:
The output of this definition => 00:00:00
DateTime time = DateTime(1990, 1, 1, 0, 0, 0, 0, 0);
Then when you want to add a period to this time
time.add(const Duration(seconds: 100,milliseconds:200))
and for output =>
String timeString = DateFormat.Hms().format(time);
print(timeString);
Result =>> 00:01:40