toDate function

DateTime? toDate(
  1. String? datetime, {
  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(String? datetime, {String? format}) {
  if (isNullOrEmpty(datetime) || datetime == 'null') return null;

  DateTime? result;
  try {
    DateFormat formattedDate = DateFormat(format);
    if (format is String) result = formattedDate.parse(datetime!);
  } on FormatException catch (e) {
    Log().debug(e.toString(),
        caller: 'static DateTime? toDate(String? datetime, {String? format})');
  } catch (e) {
    result = null;
    Log().debug(e.toString(),
        caller:
            'helper/string.dart => DateTime toDate(String date, String format) => DateFormat(format).parse(date)');
  }

  try {
    result ??= DateTime.parse(datetime!);
  } on FormatException catch (e) {
    Log().debug(e.toString(), caller: 'Invalid Format $e');
  } catch (e) {
    result = null;
    Log().debug(e.toString(),
        caller:
            'helper/string.dart => DateTime toDate(String date, String format) => DateTime.tryParse(date)');
  }
  return result;
}