formatDuration static method

String formatDuration(
  1. Duration duration
)

格式化时间 duration 为 "HH:mm:ss" 或 "mm:ss" 格式

Format the given duration into "HH:mm:ss" or "mm:ss" format. If the duration is less than 1 hour, the hour part will be omitted.

Implementation

static String formatDuration(Duration duration) {
  // Extract time components once to avoid redundant calculations
  final int totalSeconds = duration.inSeconds;
  final int hours = totalSeconds ~/ 3600; // Total hours (integer division)
  final int minutes = (totalSeconds % 3600) ~/ 60; // Remaining minutes
  final int seconds = totalSeconds % 60; // Remaining seconds

  // Format each component with leading zeros
  final String formattedHours = hours.toString().padLeft(2, '0');
  final String formattedMinutes = minutes.toString().padLeft(2, '0');
  final String formattedSeconds = seconds.toString().padLeft(2, '0');

  // Return formatted string based on whether hours are present
  if (hours > 0) {
    // Include hours if duration is 1 hour or more
    return '$formattedHours:$formattedMinutes:$formattedSeconds';
  } else {
    // Omit hours if duration is less than 1 hour
    return '$formattedMinutes:$formattedSeconds';
  }
}