normalizeDate function

int normalizeDate(
  1. dynamic date
)

Converts a date string or number (seconds since epoch) to seconds since epoch.

Implementation

int normalizeDate(dynamic date) {
  if (date is int) {
    return date;
  } else if (date is String) {
    try {
      // Attempt to parse as ISO 8601 String
      final dt = DateTime.parse(date);
      return dt.millisecondsSinceEpoch ~/ 1000;
    } catch (e) {
      // If parsing fails, try parsing as seconds or milliseconds
      final numValue = int.tryParse(date);
      if (numValue != null) {
        // Heuristic: If the number is very large, assume milliseconds
        if (numValue > 9999999999) {
          // Arbitrary threshold (around year 2286)
          return numValue ~/ 1000;
        } else {
          return numValue; // Assume it's already seconds
        }
      }
      throw FormatException('Invalid date format: $date');
    }
  } else if (date is DateTime) {
    return date.millisecondsSinceEpoch ~/ 1000;
  }
  throw ArgumentError('Invalid date type: ${date.runtimeType}');
}