toTimeSpan function

String toTimeSpan(
  1. Duration duration
)

Implementation

String toTimeSpan(Duration duration) {
  StringBuffer sb = StringBuffer("P");

  double totalSeconds = duration.inMilliseconds / 1000;
  int wholeSeconds = totalSeconds.toInt();
  int seconds = wholeSeconds;
  int sec = (seconds >= 60 ? seconds % 60 : seconds);
  int min = (seconds = (seconds ~/ 60)) >= 60 ? seconds % 60 : seconds;
  int hours = (seconds = (seconds ~/ 60)) >= 24 ? seconds % 24 : seconds;
  int days = seconds ~/ 24;
  double remainingSecs = sec + (totalSeconds - wholeSeconds);

  if (days > 0) sb.write("${days}D");

  if (days == 0 || hours + min + sec + remainingSecs > 0) {
    sb.write("T");
    if (hours > 0) sb.write("${hours}H");

    if (min > 0) sb.write("${min}M");

    if (remainingSecs > 0) {
      String secFmt = remainingSecs.toStringAsFixed(7);
      secFmt = trimEnd(secFmt, '0');
      secFmt = trimEnd(secFmt, '.');
      sb.write(secFmt);
      sb.write("S");
    } else if (sb.length == 2) { //PT
      sb.write("0S");
    }
  }

  String xsdDuration = sb.toString();
  return xsdDuration;
}