toString method

  1. @override
String toString()
override

Returns the duration in ISO 8601 duration format.

Implementation

@override
String toString() {
  if (_days == 0 && _months == 0 && _microseconds == 0) {
    return 'PT0S';
  }

  final y = years;
  final m = _months - y * 12;
  final d = _days;
  var str =
      'P${y != 0 ? '${y}Y' : ''}${m != 0 ? '${m}M' : ''}${d != 0 ? '${d}D' : ''}';
  if (_microseconds != 0) {
    var us = _microseconds;
    final h = us ~/ Duration.microsecondsPerHour;
    us -= h * Duration.microsecondsPerHour;
    final min = us ~/ Duration.microsecondsPerMinute;
    us -= min * Duration.microsecondsPerMinute;
    final s = us ~/ Duration.microsecondsPerSecond;
    us -= s * Duration.microsecondsPerSecond;
    str += 'T${h != 0 ? '${h}H' : ''}${min != 0 ? '${min}M' : ''}';
    if (s != 0 || us != 0) {
      str += '${s.isNegative || us.isNegative ? '-' : ''}${s.abs()}'
          '${us != 0 ? '.${us.abs().toString().padLeft(6, '0').replaceFirst(RegExp(r'0+$'), '')}' : ''}S';
    }
  }
  return str;
}