fromIsoString function

Duration fromIsoString(
  1. String str
)

将ISO_8601时间间隔转换为 Duration

fromIsoString('PT10H3S')

Implementation

Duration fromIsoString(String str) {
  var parts = _splitDurationRegex.firstMatch(str);
  if (parts == null) return Duration.zero;

  var timeEmpty = !(parts[6] != null || parts[7] != null || parts[8] != null);
  var dateTimeEmpty =
      timeEmpty && !(parts[2] != null || parts[3] != null || parts[4] != null);
  if (dateTimeEmpty || timeEmpty && parts[5] != null) return Duration.zero;

  var negative = parts[1] != null;
  var years = int.parse(parts[2] ?? '0');
  var months = int.parse(parts[3] ?? '0');
  var days = int.parse(parts[4] ?? '0');
  var hours = int.parse(parts[6] ?? '0');
  var minutes = int.parse(parts[7] ?? '0');
  var seconds = int.parse(parts[8] ?? '0');

  // @TODO: Duration类实现不支持年份和月份,对于ISO_8601中含年份和月份的信息
  //   会存在问题.
  assert(years == 0);
  assert(months == 0);

  return negative
      ? Duration(
          days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
      : Duration(days: days, hours: hours, minutes: minutes, seconds: seconds);
}