parse method

  1. @override
Duration? parse(
  1. String? value
)
override

Implementation

@override
Duration? parse(String? value) {
  if (value == null || !isValid(value)) {
    return Duration.zero;
  }

  String input = value.split(' ').join();
  RegExp onlyNumbers = RegExp(r'\d+');

  RegExp yearRegex = RegExp('(\\d)+$yearSuffix');
  RegExp monthRegex = RegExp('(\\d)+$monthSuffix');
  RegExp dayRegex = RegExp('(\\d)+$daySuffix');
  RegExp hourRegex = RegExp('(\\d)+$hourSuffix');
  RegExp minuteRegex = RegExp('(\\d)+$minuteSuffix');
  RegExp secondRegex = RegExp('(\\d)+$secondSuffix');
  RegExp millisecondRegex = RegExp('(\\d)+$millisecondSuffix');

  String yearsString = yearRegex.firstMatch(input)?.group(0) ?? '';
  String monthsString = monthRegex.firstMatch(input)?.group(0) ?? '';
  String daysString = dayRegex.firstMatch(input)?.group(0) ?? '';
  String hoursString = hourRegex.firstMatch(input)?.group(0) ?? '';
  String minutesString = minuteRegex.firstMatch(input)?.group(0) ?? '';
  String secondsString = secondRegex.firstMatch(input)?.group(0) ?? '';
  String millisecondsString =
      millisecondRegex.firstMatch(input)?.group(0) ?? '';

  int years =
      int.tryParse(onlyNumbers.firstMatch(yearsString)?.group(0) ?? '') ?? 0;
  int months =
      int.tryParse(onlyNumbers.firstMatch(monthsString)?.group(0) ?? '') ?? 0;
  int days =
      int.tryParse(onlyNumbers.firstMatch(daysString)?.group(0) ?? '') ?? 0;
  int hours =
      int.tryParse(onlyNumbers.firstMatch(hoursString)?.group(0) ?? '') ?? 0;
  int minutes =
      int.tryParse(onlyNumbers.firstMatch(minutesString)?.group(0) ?? '') ??
          0;
  int seconds =
      int.tryParse(onlyNumbers.firstMatch(secondsString)?.group(0) ?? '') ??
          0;
  int milliseconds = int.tryParse(
        onlyNumbers.firstMatch(millisecondsString)?.group(0) ?? '',
      ) ??
      0;

  return Duration(
    days: days + 30 * months + 365 * years,
    hours: hours,
    minutes: minutes,
    seconds: seconds,
    milliseconds: milliseconds,
  );
}