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

Issue

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?

Solution

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);
}

Answered By – Richard Heap

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *