parseWebDateString static method

DateTime parseWebDateString(
  1. String body, {
  2. String? dateHeader,
})

Parses an HTTP-date (RFC 1123), Cloudflare trace (ts=...), or ISO-8601 string into a UTC DateTime without external dependencies.

Implementation

static DateTime parseWebDateString(String body, {String? dateHeader}) {
  final trimmed = body.trim().replaceAll('"', '');

  // 1. Try RFC 1123 HTTP-date (e.g. "Wed, 14 Oct 2026 08:00:00 GMT")
  final rfcMatch = _rfc1123RegExp.firstMatch(trimmed);
  if (rfcMatch != null) {
    final day = int.parse(rfcMatch.group(1)!);
    final month = _months[rfcMatch.group(2)!];
    if (month != null) {
      final year = int.parse(rfcMatch.group(3)!);
      final hour = int.parse(rfcMatch.group(4)!);
      final minute = int.parse(rfcMatch.group(5)!);
      final second = int.parse(rfcMatch.group(6)!);
      return DateTime.utc(year, month, day, hour, minute, second);
    }
  }

  // 2. Try Cloudflare trace format (e.g. "ts=1760428800.123")
  final cfMatch = _cloudflareTraceRegExp.firstMatch(trimmed);
  if (cfMatch != null) {
    final seconds = int.parse(cfMatch.group(1)!);
    final fracStr = (cfMatch.group(2) ?? '').padRight(6, '0').substring(0, 6);
    final micros = int.parse(fracStr);
    return DateTime.fromMicrosecondsSinceEpoch(
      seconds * 1000000 + micros,
      isUtc: true,
    );
  }

  // 3. Try ISO-8601
  final isoParsed = DateTime.tryParse(trimmed);
  if (isoParsed != null) {
    return isoParsed.toUtc();
  }

  // 4. Fallback to HTTP Date header if present
  if (dateHeader != null && dateHeader.isNotEmpty) {
    final headerMatch = _rfc1123RegExp.firstMatch(dateHeader.trim());
    if (headerMatch != null) {
      final day = int.parse(headerMatch.group(1)!);
      final month = _months[headerMatch.group(2)!];
      if (month != null) {
        final year = int.parse(headerMatch.group(3)!);
        final hour = int.parse(headerMatch.group(4)!);
        final minute = int.parse(headerMatch.group(5)!);
        final second = int.parse(headerMatch.group(6)!);
        return DateTime.utc(year, month, day, hour, minute, second);
      }
    }
  }

  throw FormatException('Unsupported time format: "$body"');
}