toDate function

DateTime? toDate(
  1. dynamic value, {
  2. String? format,
})

Converts a String to a formattable DateTime object

More info on supported formats can be found in DateFormat and DateTime

Implementation

DateTime? toDate(dynamic value, {String? format}) {

  // missing or empty value
  if (isNullOrEmpty(value)) return null;

  // already a date
  if (value is DateTime) return value;

  // value is time of day
  if (value is TimeOfDay) {
    DateTime now = DateTime.now();
    return DateTime(now.year, now.month, now.day, value.hour, value.minute);
  }

  // not a string
  if (value is! String) return null;

  try {
    return format != null ? DateFormat(format).parse(value) : DateTime.parse(value);
  } catch (e) {
    return null;
  }
}