toDate static method

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

static DateTime? toDate(String? datetime, {String? format})
{
  if (S.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
  {
    if (result == null)
    {
      //tryparse returns null if it fails so this was never caught.
      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;
}