parseTime function

Duration parseTime(
  1. String input
)

Parses duration string formatted by Duration.toString() to Duration. The string should be of form hours:minutes:seconds.microseconds

Example: parseTime('245:09:08.007006');

Implementation

Duration parseTime(String input) {
  final parts = input.split(':');

  if (parts.length != 3) throw FormatException('Invalid time format');

  int days;
  int hours;
  int minutes;
  int seconds;
  int milliseconds;
  int microseconds;

  {
    final p = parts[2].split('.');

    if (p.length != 2) throw FormatException('Invalid time format');

    // If fractional seconds is passed, but less than 6 digits
    // Pad out to the right so we can calculate the ms/us correctly
    final p2 = int.parse(p[1].padRight(6, '0'));
    microseconds = p2 % 1000;
    milliseconds = p2 ~/ 1000;

    seconds = int.parse(p[0]);
  }

  minutes = int.parse(parts[1]);

  {
    int p = int.parse(parts[0]);
    hours = p % 24;
    days = p ~/ 24;
  }

  // TODO verify that there are no negative parts

  return Duration(
      days: days,
      hours: hours,
      minutes: minutes,
      seconds: seconds,
      milliseconds: milliseconds,
      microseconds: microseconds);
}