toDateTime function

DateTime? toDateTime(
  1. dynamic str
)

Implementation

DateTime? toDateTime(dynamic str) {
  if (str == null) {
    return null;
  }
  if (str is DateTime) {
    return str;
  }
  if (str is String) {
    if (str.isEmpty) {
      return null;
    }
    if (str.contains('/')) {
      List<String> parts = str.split(' ');
      if (parts.isEmpty) {
        return null;
      }
      str = parts[0].split('/').reversed.join('-');
      if (parts.length > 1) {
        for (String part in parts.sublist(1)) {
          if (str == null || str.isEmpty) {
            str = part;
          } else {
            str += " $part";
          }
        }
      }
    } else {
      str = str.replaceFirst('T', " ");
    }
    return DateTime.parse(str);
  }
  throw Exception("Unkown StringToDateTime type '$str'");
}