format method

String format(
  1. String formatStr
)

Formats the duration with a custom format string.

Supported tokens:

  • Y or YY - Years
  • M or MM - Months
  • D or DD - Days
  • H or HH - Hours
  • m or mm - Minutes
  • s or ss - Seconds

Other characters pass through as literals. Use [text] to escape text that might contain token characters.

Implementation

String format(String formatStr) {
  final buffer = StringBuffer();
  var i = 0;

  while (i < formatStr.length) {
    // Handle escaped text [...]
    if (formatStr[i] == '[') {
      final closeIndex = formatStr.indexOf(']', i);
      if (closeIndex != -1) {
        buffer.write(formatStr.substring(i + 1, closeIndex));
        i = closeIndex + 1;
        continue;
      }
    }

    final remaining = formatStr.substring(i);
    final token = _matchDurationToken(remaining);
    if (token != null) {
      buffer.write(_formatDurationToken(token));
      i += token.length;
    } else {
      buffer.write(formatStr[i]);
      i++;
    }
  }

  return buffer.toString();
}