parseStandardDuration function

Duration parseStandardDuration(
  1. String durationString
)

Implementation

Duration parseStandardDuration(String durationString) {
  if (durationString.isEmpty) {
    throw Exception('Duration string must be non-empty: $durationString');
  }

// Process and remove a negative sign, if it exists.
  bool isNegative = durationString[0] == '-';
  if (isNegative) {
    durationString = durationString.substring(1);
  }

  final timeComponents = durationString.split(':');
  final secondsWithFraction = timeComponents.removeLast();
  final seconds = double.parse(secondsWithFraction).truncate();
  final microseconds = ((double.parse(secondsWithFraction) - seconds) * _microsPerSecond)
      .truncate(); // truncate shouldn't change anything. we just need an int.
  String minutes = '';
  String hours = '';
  if (timeComponents.isNotEmpty) {
    minutes = timeComponents.removeLast();
  }
  if (timeComponents.isNotEmpty) {
    hours = timeComponents.removeLast();
  }
  if (timeComponents.isNotEmpty) {
    throw Exception('A standard format duration cannot have any time components beyond hours: "$durationString"');
  }

  final signMultiplier = isNegative ? -1 : 1;
  return Duration(
    hours: (hours.isEmpty ? 0 : int.parse(hours)) * signMultiplier,
    minutes: (minutes.isEmpty ? 0 : int.parse(minutes)) * signMultiplier,
    seconds: seconds * signMultiplier,
    microseconds: microseconds * signMultiplier,
  );
}