toString 方法

String toString()
重写

返回一个表示此 Duration 的字符串。

返回的字符串包含小时、分钟、秒和微秒,格式为:H:MM:SS.mmmmmm。例如:

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

实现

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";
}