isDate method Null safety

bool? isDate()

Checks whether the String is valid Date:

Valid formats

  • dd/mm/yyyy
  • dd-mm-yyyyy
  • dd.mm.yyyy
  • yyyy-mm-dd
  • yyyy-mm-dd hrs
  • 20120227 13:27:00
  • 20120227T132700
  • 20120227
  • +20120227
  • 2012-02-27T14Z
  • 2012-02-27T14+00:00
  • -123450101 00:00:00 Z": in the year -12345
  • 2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z

Implementation

bool? isDate() {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return false;
  }
  var regex = RegExp(
      r'^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$');
  if (regex.hasMatch(this!)) {
    return true;
  }
  try {
    DateTime.parse(this!);
    return true;
  } on FormatException {
    return false;
  }
}