timestampFromRfc3339 static method

({int nanos, int seconds}) timestampFromRfc3339(
  1. String input
)

Implementation

static ({int seconds, int nanos}) timestampFromRfc3339(String input) {
  final re = RegExp(
    r'^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$',
  );

  final match = re.firstMatch(input);
  if (match == null) {
    throw ArgumentException.invalidOperationArguments(
      "timestampFromRfc3339",
      reason: 'Invalid RFC3339 timestamp',
    );
  }

  final fraction = match.group(2);

  int nanos = 0;
  if (fraction != null) {
    nanos = int.parse(fraction.padRight(9, '0'));
  }

  // Parse without the fractional part to preserve nanoseconds.
  final dt = DateTime.parse('${match.group(1)}${match.group(3)}').toUtc();

  return (seconds: dt.millisecondsSinceEpoch ~/ 1000, nanos: nanos);
}