toDuration method

Duration toDuration()

Parses a time string (e.g. "MM:SS" or "HH:MM:SS") into a Duration.

Throws an Exception if the format is invalid.

Example:

'01:30'.toDuration(); // Duration(minutes: 1, seconds: 30)
'01:15:20'.toDuration(); // Duration(hours: 1, minutes: 15, seconds: 20)

Implementation

Duration toDuration() {
  final chunks = split(':');
  if (chunks.length == 1) {
    throw Exception('Invalid duration string: $this');
  } else if (chunks.length == 2) {
    return Duration(
      minutes: int.parse(chunks[0].trim()),
      seconds: int.parse(chunks[1].trim()),
    );
  } else if (chunks.length == 3) {
    return Duration(
      hours: int.parse(chunks[0].trim()),
      minutes: int.parse(chunks[1].trim()),
      seconds: int.parse(chunks[2].trim()),
    );
  } else {
    throw Exception('Invalid duration string: $this');
  }
}