toString method

String toString()
override

Returns a string representation of this Duration.

Returns a string with hours, minutes, seconds, and microseconds, in the following format: H:MM:SS.mmmmmm. For example,

var d = const Duration(days: 1, hours: 1, minutes: 33, microseconds: 500);
print(d.toString()); // 25:33:00.000500

d = const Duration(hours: 1, minutes: 10, microseconds: 500);
print(d.toString()); // 1:10:00.000500

Implementation

String toString() {
  var microseconds = inMicroseconds;
  var sign = "";
  var negative = microseconds < 0;

  var hours = microseconds ~/ microsecondsPerHour;
  microseconds = microseconds.remainder(microsecondsPerHour);

  // Correcting for being negative after first division, instead of before,
  // to avoid negating min-int, -(2^31-1), of a native int64.
  if (negative) {
    hours = 0 - hours; // Not using `-hours` to avoid creating -0.0 on web.
    microseconds = 0 - microseconds;
    sign = "-";
  }

  var minutes = microseconds ~/ microsecondsPerMinute;
  microseconds = microseconds.remainder(microsecondsPerMinute);

  var minutesPadding = minutes < 10 ? "0" : "";

  var seconds = microseconds ~/ microsecondsPerSecond;
  microseconds = microseconds.remainder(microsecondsPerSecond);

  var secondsPadding = seconds < 10 ? "0" : "";

  // Padding up to six digits for microseconds.
  var microsecondsText = microseconds.toString().padLeft(6, "0");

  return "$sign$hours:"
      "$minutesPadding$minutes:"
      "$secondsPadding$seconds."
      "$microsecondsText";
}