tryParse static method

Iso8601Duration? tryParse(
  1. String input, {
  2. int maxInputLength = 24,
})

Parse an ISO 8601 duration input string into a Iso8601Duration.

maxInputLength is the maximum number of input characters

Examples:

  • P1S - One second
  • P1M - One month
  • P1MT1M - One month and one minute
  • P1Y2M3DT4H5M6S - One year, two months, three days, four hours, five minutes, six seconds

Returns (null, false) if the input is not a valid duration.

Implementation

static Iso8601Duration? tryParse(String input, {int maxInputLength = 24}) {
  // Guard the RegEx from dodgy strings
  if (input.substring(0, 1) != 'P' ||
      input.length > maxInputLength ||
      [
        'Y',
        'M',
        'D',
        'H',
        'S',
        'T',
      ].contains(input.substring(input.length - 2))) {
    return null;
  }

  var match = iso8601Duration.firstMatch(input);
  if (match == null) {
    return null;
  }

  int? seconds = int.tryParse(match.namedGroup('seconds') ?? '0');
  int? minutes = int.tryParse(match.namedGroup('minutes') ?? '0');
  int? hours = int.tryParse(match.namedGroup('hours') ?? '0');
  int? days = int.tryParse(match.namedGroup('days') ?? '0');
  int? months = int.tryParse(match.namedGroup('months') ?? '0');
  int? years = int.tryParse(match.namedGroup('years') ?? '0');

  if ([seconds, minutes, hours, days, months, years].any((e) => e == null)) {
    return null;
  }

  return Iso8601Duration._(
    years: years!,
    months: months!,
    days: days!,
    hours: hours!,
    minutes: minutes!,
    seconds: seconds!,
  );
}