rfc3339ToTimestamp function

Map<String, Object?> rfc3339ToTimestamp(
  1. String rfc3339
)

Parses an RFC 3339 string into a google.protobuf.Timestamp.

Accepts strings like "1972-01-01T10:00:20.021Z" or without fractional seconds like "2000-01-01T00:00:00Z".

Returns {"seconds": int, "nanos": int}.

Implementation

Map<String, Object?> rfc3339ToTimestamp(String rfc3339) {
  final dt = DateTime.parse(rfc3339);
  final seconds = dt.millisecondsSinceEpoch ~/ 1000;

  // Extract fractional seconds from the string to preserve full nanosecond
  // precision (DateTime only holds microseconds).
  int nanos = 0;
  final dotIndex = rfc3339.indexOf('.');
  if (dotIndex != -1) {
    // Find the end of the fractional part (before 'Z' or timezone offset).
    int endIndex = rfc3339.length;
    for (int i = dotIndex + 1; i < rfc3339.length; i++) {
      if (rfc3339[i] == 'Z' ||
          rfc3339[i] == 'z' ||
          rfc3339[i] == '+' ||
          rfc3339[i] == '-') {
        endIndex = i;
        break;
      }
    }
    final fracStr = rfc3339.substring(dotIndex + 1, endIndex).padRight(9, '0');
    nanos = int.parse(fracStr.substring(0, 9));
  }

  return {'seconds': seconds, 'nanos': nanos};
}