1

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?

matte_colo
  • 335
  • 1
  • 6
  • 18

2 Answers2

4

According to this answer you can implement a method like this:

String printDuration(Duration duration) {
  String twoDigits(int n) {
    if (n >= 10) return "$n";
    return "0$n";
  }

  String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
  String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
  if (duration.inHours > 0)
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  else
    return "$twoDigitMinutes:$twoDigitSeconds";
}
Zahra Jamshidi
  • 681
  • 6
  • 9
-1

To split time in milliseconds into other units you can use Duration class

To turn numbers into strings with leading zeros (and any other string formating) use c-style sprintf which takes a string format with % where missing values are, and a List of those values. read up on the format by googling printf, but basically %05i would mean make this integer take up 5 spaces and use leading 0.

import 'package:sprintf/sprintf.dart';


String convertTime(int timeInMilliseconds) {
  Duration timeDuration = Duration(milliseconds: timeInMilliseconds);
  int centiseconds = timeDuration.inMilliseconds ~/ 10;
  int seconds = timeDuration.inSeconds;
  int minutes = timeDuration.inMinutes;
  int hours = timeDuration.inHours;

  if (hours > 0){
    return sprintf('%i:%02i:%02i.%02i', [hours, minutes, seconds, centiseconds]);
  }else if(minutes > 0){
    return sprintf('i:%02i.%02i', [minutes, seconds, centiseconds]);
  }else {
    return sprintf('i.%02i', [seconds, centiseconds]);
  }    
}

I hope this helps

drpawelo
  • 2,348
  • 23
  • 17