toDateTime static method

DateTime toDateTime(
  1. dynamic object, {
  2. Object? mapKey,
  3. int? listIndex,
  4. String? format,
  5. String? local,
})

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, {
  Object? mapKey,
  int? listIndex,
  String? format,
  String? local,
}) {
  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]);
  }
  if (listIndex != null && object is List<dynamic>) {
    return toDateTime(object.of(listIndex));
  }
  try {
    if (format.isEmptyOrNull) return DateTime.parse('$object');
    return '$object'.toDateWithFormat(
      format!,
    );
  } catch (e, s) {
    throw ParsingException(
      error: e,
      parsingInfo: 'toDateTime',
      stackTrace: s,
    );
  }
}