parseDuration static method

Duration? parseDuration(
  1. Object? value, [
  2. Duration? def
])

Tries to parse a Duration.

  • Returns def if value is invalid.

Implementation

static Duration? parseDuration(Object? value, [Duration? def]) {
  if (value == null) return def;

  if (value is Duration) {
    return value;
  } else if (value is int) {
    return Duration(milliseconds: value);
  } else {
    var s = '$value'.trim().replaceAll(_regexpSpaces, ':');

    // A leading `-` negates the whole [Duration]. It can't be left to
    // `split`, since `-` is also a field separator (see
    // [_regexpTimeSeparators]) and the sign would be silently dropped.
    var negative = s.startsWith('-');
    if (negative) {
      s = s.substring(1);
    }

    var parts = s.split(_regexpTimeSeparators);

    var ns = parts.map((e) => int.tryParse(e) ?? 0).toList();

    var hour = ns.isNotEmpty ? ns[0] : 0;
    var min = ns.length > 1 ? ns[1] : 0;
    var sec = ns.length > 2 ? ns[2] : 0;
    var ms = ns.length > 3 ? ns[3] : 0;
    var mc = ns.length > 4 ? ns[4] : 0;

    var duration = Duration(
      hours: hour,
      minutes: min,
      seconds: sec,
      milliseconds: ms,
      microseconds: mc,
    );

    return negative ? -duration : duration;
  }
}