parseDate static method

DateTime parseDate(
  1. Object? value
)

Parses a civil date as UTC solely for component validation/comparison. Convert its components to a local calendar date when displaying a picker; do not convert this validation value with toLocal().

Implementation

static DateTime parseDate(Object? value) {
  if (value is! String ||
      value.length != 10 ||
      !RegExp(r'^[0-9]{4}-[0-9]{2}-[0-9]{2}$').hasMatch(value)) {
    throw const FormatException('Expected a date in YYYY-MM-DD format.');
  }
  final year = int.parse(value.substring(0, 4));
  final month = int.parse(value.substring(5, 7));
  final day = int.parse(value.substring(8, 10));
  if (year < 1 || month < 1 || month > 12 || day < 1 || day > 31) {
    throw const FormatException('Expected a valid Gregorian date.');
  }
  final date = DateTime.utc(year, month, day);
  if (date.year != year || date.month != month || date.day != day) {
    throw const FormatException('Expected a valid Gregorian date.');
  }
  return date;
}