timestampToRfc3339 function

String timestampToRfc3339(
  1. Map<String, Object?> timestamp
)

Converts a google.protobuf.Timestamp to an RFC 3339 string.

A Timestamp contains "seconds" (int64, seconds since Unix epoch) and optional "nanos" (int32, sub-second nanoseconds in [0, 999999999]).

Output format: "1972-01-01T10:00:20.021Z" (trailing zeros in the fractional part are trimmed; the fraction is omitted entirely when nanos is zero).

Implementation

String timestampToRfc3339(Map<String, Object?> timestamp) {
  final seconds = _toInt(timestamp['seconds'] ?? 0);
  final nanos = _toInt(timestamp['nanos'] ?? 0);

  final dt = DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true);

  final datePart = '${_pad4(dt.year)}-${_pad2(dt.month)}-${_pad2(dt.day)}';
  final timePart = '${_pad2(dt.hour)}:${_pad2(dt.minute)}:${_pad2(dt.second)}';

  if (nanos == 0) {
    return '${datePart}T${timePart}Z';
  }

  // Format nanos as 3, 6, or 9 digits depending on precision needed.
  final nanoStr = nanos.toString().padLeft(9, '0');
  // Trim trailing zeros but keep at least 3 digits for millis.
  String fractional = nanoStr;
  // Remove trailing zeros.
  while (fractional.length > 1 && fractional.endsWith('0')) {
    fractional = fractional.substring(0, fractional.length - 1);
  }

  return '${datePart}T$timePart.${fractional}Z';
}