toIsoString function

String toIsoString(
  1. Duration duration
)

Duration 转换为ISO_8601格式

toIsoString(Duration(seconds: 100)) == 'PT1M40S'

Implementation

String toIsoString(Duration duration) {
  if (duration.inSeconds == 0) {
    return 'PT0S';
  }

  var years = 0;
  var months = 0;
  var days = duration.inDays.abs();
  var hours = duration.inHours.remainder(Duration.hoursPerDay).abs();
  var minutes = duration.inMinutes.remainder(Duration.minutesPerHour).abs();
  var seconds = duration.inSeconds.remainder(Duration.secondsPerMinute).abs();

  var res = [];

  // Add sign and 'P' prefix.
  if (duration.inSeconds < 0) {
    res.add('-');
  }
  res.add('P');

  // Add date.
  if (years > 0) {
    res.add('${years}Y');
  }
  if (months > 0) {
    res.add('${months}M');
  }
  if (days > 0) {
    res.add('${days}D');
  }

  // Add time.
  if (hours > 0 || minutes > 0 || seconds > 0) {
    res.add('T');
    if (hours > 0) {
      res.add('${hours}H');
    }
    if (minutes > 0) {
      res.add('${minutes}M');
    }
    if (seconds > 0) {
      res.add('${seconds}S');
    }
  }

  return res.join('');
}