toDateTime static method

DateTime toDateTime(
  1. dynamic object, {
  2. dynamic mapKey,
  3. int? listIndex,
  4. String? format,
  5. String? locale,
  6. bool autoDetectFormat = false,
  7. bool useCurrentLocale = false,
  8. bool utc = false,
})

Converts an object to a DateTime.

  • If the object is a string representing a valid DateTime, it converts it to a DateTime object.
  • If the object is already a DateTime, it is returned as-is.
  • If the object is null, throws a ParsingException with a nullObject error.
  • If the conversion to DateTime fails (e.g., invalid format), throws a ParsingException.

object The object to be converted to a DateTime. format (Optional) Specify the format if the object is a string representing a DateTime. mapKey (Optional) Specifies the key to extract values from a Map object. listIndex (Optional) Specifies the index to extract elements from a List object.

Returns a DateTime if conversion is successful. Throws a ParsingException if the conversion fails or the object is null.

Example usage:

final object1 = '2023-06-26T12:00:00Z';
final dateTime1 = ConvertObject.toDateTime(object1); // 2023-06-26 12:00:00.000Z

final object2 = DateTime(2023, 6, 26, 12, 0, 0);
final dateTime2 = ConvertObject.toDateTime(object2); // 2023-06-26 12:00:00.000

final object3 = 'Invalid DateTime';
final dateTime3 = ConvertObject.toDateTime(object3); // ParsingException (logs an error)

final object4 = null;
final dateTime4 = ConvertObject.toDateTime(object4); // ParsingException (null object)

Implementation

static DateTime toDateTime(
  dynamic object, {
  dynamic mapKey,
  int? listIndex,
  String? format,
  String? locale,
  bool autoDetectFormat = false,
  bool useCurrentLocale = false,
  bool utc = false,
}) {
  if (object == null) {
    throw ParsingException.nullObject(
      parsingInfo: 'toDateTime',
      stackTrace: StackTrace.current,
    );
  }
  if (object is DateTime) return object;
  if (mapKey != null && object is Map<dynamic, dynamic>) {
    return toDateTime(
      object[mapKey],
      format: format,
      locale: locale,
      useCurrentLocale: useCurrentLocale,
      utc: utc,
    );
  }
  if (listIndex != null && object is List<dynamic>) {
    return toDateTime(
      object.of(listIndex),
      format: format,
      locale: locale,
      useCurrentLocale: useCurrentLocale,
      utc: utc,
    );
  }
  try {
    if (format != null) return '$object'.toDateFormatted(format, locale, utc);
    if (autoDetectFormat) {
      return '$object'.toDateAutoFormat(
        locale: locale,
        useCurrentLocale: useCurrentLocale,
        utc: utc,
      );
    }
    return '$object'.toDateTime;
  } catch (e, s) {
    throw ParsingException(
      error: e,
      parsingInfo: 'toDateTime',
      stackTrace: s,
    );
  }
}