I'm using Dart (with Flutter) and I need to convert a time expressed in milliseconds to string.
When converting I want to show:
- centiseconds
- seconds
- minutes
- hours
Centiseconds and seconds must always be shown, while minutes and hour only if they're greater than 0.
Example of expected outputs:
time = 0 => "0.00"
time = 123 => "0.12"
time = 9012 => "9.01"
time = 19023 => "19.02"
time = 123123 => "2:03.12"
time = 5 * 3600000 => "5:00:00.00"
The leftmost non zero value can be one or more digits, while the others must be two digits.
This is my code:
String convertTime(int time) {
int centiseconds = (time % 1000) ~/ 10;
time ~/= 1000;
int seconds = time % 60;
time ~/= 60;
int minutes = time % 60;
time ~/= 60;
int hours = time;
if (hours > 0) {
return "$hours:${_twoDigits(minutes)}:${_twoDigits(seconds)}.${_twoDigits(centiseconds)}";
} else if (minutes > 0) {
return "$minutes:${_twoDigits(seconds)}.${_twoDigits(centiseconds)}";
} else {
return "$seconds.${_twoDigits(centiseconds)}";
}
}
String _twoDigits(int time) {
return "${time<10?'0':''}$time";
}
How can I improve my code? What is the most efficient way to perform this conversion?