Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Duration like string to a real Duration in Flutter?

Tags:

flutter

As the title says, I got a string '01:23.290', it looks like a Duration, but not. Now I need to use this to compare with a real Duration, and I don't how to deal with it. Is there any methods?

like image 906
Felix Wang Avatar asked Feb 24 '19 13:02

Felix Wang


People also ask

How do you display time duration in flutter?

If we are dealing with smaller durations and needed only minutes and seconds: format(Duration d) => d. toString().


2 Answers

Use a parsing function like this, then use the comparison methods of Duration:

Duration parseDuration(String s) {
  int hours = 0;
  int minutes = 0;
  int micros;
  List<String> parts = s.split(':');
  if (parts.length > 2) {
    hours = int.parse(parts[parts.length - 3]);
  }
  if (parts.length > 1) {
    minutes = int.parse(parts[parts.length - 2]);
  }
  micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
  return Duration(hours: hours, minutes: minutes, microseconds: micros);
}
like image 141
Richard Heap Avatar answered Sep 18 '22 17:09

Richard Heap


Package duration provides functions parseTime and tryParseTime to parse duration strings obtained by Duration().toString().

Usage is straight forward:

print(parseTime(Duration(hours: 5, seconds: 10, milliseconds: 567).toString()));
like image 38
Ravi Teja Gudapati Avatar answered Sep 22 '22 17:09

Ravi Teja Gudapati