tryParseAsciiDateTime function

DateTime? tryParseAsciiDateTime(
  1. Uint8List data
)

Fast-path parse for common SQL / ISO datetime ASCII forms.

Accepts YYYY-MM-DD, YYYY-MM-DD[ T]HH:MM:SS[.fraction], and optional trailing Z. Returns null when the pattern does not match (caller falls back to DateTime.tryParse).

Implementation

DateTime? tryParseAsciiDateTime(Uint8List data) {
  if (data.isEmpty || !isAsciiBytes(data)) {
    return null;
  }
  var start = 0;
  var end = data.length;
  while (start < end && _isAsciiSpace(data[start])) {
    start++;
  }
  while (end > start && _isAsciiSpace(data[end - 1])) {
    end--;
  }
  final len = end - start;
  if (len < 10) {
    return null;
  }
  // Normalize space separator to 'T' via fromCharCodes for tryParse when
  // the shape looks like a datetime; for pure date use direct fields.
  if (!_looksLikeAsciiDatePrefix(data, start)) {
    return null;
  }
  if (len == 10) {
    final y = _readAsciiDigits(data, start, 4);
    final mo = _readAsciiDigits(data, start + 5, 2);
    final d = _readAsciiDigits(data, start + 8, 2);
    if (y == null || mo == null || d == null) {
      return null;
    }
    if (data[start + 4] != 0x2d || data[start + 7] != 0x2d) {
      return null;
    }
    return DateTime(y, mo, d);
  }
  // Build the string without allocating a List<int> intermediate buffer.
  // When the separator at position 10 is a space, split around it; otherwise
  // convert the slice directly. DateTime.tryParse accepts ISO-8601 with 'T'.
  if (data[start + 10] == 0x20) {
    return DateTime.tryParse(
      '${String.fromCharCodes(data, start, start + 10)}'
      'T'
      '${String.fromCharCodes(data, start + 11, start + len)}',
    );
  }
  return DateTime.tryParse(String.fromCharCodes(data, start, start + len));
}