tryParseDuration function

Duration? tryParseDuration(
  1. String? value
)

Tries to parse a Duration from a String.

The string must be in the same format used by either Duration.toString (e.g. '1:23:45.123456') or readableDuration.

Ignores surrounding whitespace.

Returns null if the input is not recognized.

Implementation

Duration? tryParseDuration(String? value) {
  if (value == null) {
    return null;
  }

  value = value.trim();
  if (value.isEmpty) {
    return null;
  }

  var match = _durationRegExp.firstMatch(value) ??
      _readableDurationRegExp.firstMatch(value);
  if (match == null) {
    return null;
  }

  var isNegative = match.namedGroup('sign') == '-';

  var daysString = match.namedGroup('days');
  var hoursString = match.namedGroup('hours');
  var minutesString = match.namedGroup('minutes');
  var secondsString = match.namedGroup('seconds');
  var subsecondsString = match.namedGroup('subseconds');

  var days = (daysString == null) ? 0 : int.parse(daysString);
  var hours = (hoursString == null) ? 0 : int.parse(hoursString);
  var minutes = (minutesString == null) ? 0 : int.parse(minutesString);
  var seconds = (secondsString == null) ? 0 : int.parse(secondsString);

  var microseconds = 0;
  if (subsecondsString != null) {
    const microsecondDigits = 6;
    const fixedLength = microsecondDigits + 1;
    microseconds = int.parse(
          subsecondsString.padRight(fixedLength, '0').substring(0, fixedLength),
        ).roundToMultipleOf(10) ~/
        10;
  }

  var duration = Duration(
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds,
    microseconds: microseconds,
  );
  return isNegative ? -duration : duration;
}