toDateTime static method

DateTime? toDateTime(
  1. dynamic v, {
  2. String format = defDateTimeFormat,
  3. String? locale,
  4. bool isUtc = false,
  5. DateTime? defaultValue,
})

Implementation

static DateTime? toDateTime(v,
    {String format = defDateTimeFormat,
    String? locale,
    bool isUtc = false,
    DateTime? defaultValue}) {
  if (v == null) return defaultValue;
  if (v is num) return DateTime.fromMillisecondsSinceEpoch(v.toInt());
  if (v is DateTime) return v;
  if (v is String) {
    final num? n = num.tryParse(v);
    if (n != null) DateTime.fromMillisecondsSinceEpoch(n.toInt());

    final df = DateFormat(format, locale);
    try {
      return df.parse(v, isUtc);
    } catch (e) {
      if (defaultValue != null) return defaultValue;
      throw Exception('Trying to convert a non-DateTime to DateTime!');
    }
  }
  if (defaultValue != null) return defaultValue;
  throw Exception('Trying to convert a non-DateTime to DateTime!');
}