formatBuddhistEra method

String formatBuddhistEra(
  1. String pattern
)

Formats the date using Buddhist Era year tokens.

Supports BBBB for 4-digit BE year and BB for 2-digit BE year. All other tokens work the same as standard format().

Implementation

String formatBuddhistEra(String pattern) {
  if (!isValid) {
    return locale.invalidDate;
  }

  // Pre-process: replace Buddhist Era tokens with escaped literals
  // before passing to the standard formatter.
  final buffer = StringBuffer();
  var i = 0;
  while (i < pattern.length) {
    if (pattern[i] == '[') {
      final closeIndex = pattern.indexOf(']', i + 1);
      if (closeIndex == -1) {
        buffer.write(pattern.substring(i));
        break;
      }
      buffer.write(pattern.substring(i, closeIndex + 1));
      i = closeIndex + 1;
    } else if (pattern.startsWith('BBBB', i)) {
      buffer.write('[${buddhistYear.toString().padLeft(4, '0')}]');
      i += 4;
    } else if (pattern.startsWith('BB', i)) {
      buffer.write('[${buddhistYearShort.toString().padLeft(2, '0')}]');
      i += 2;
    } else {
      buffer.write(pattern[i]);
      i++;
    }
  }

  return format(buffer.toString());
}