tryToDateTime function
Attempts to convert an object to a DateTime, or returns null
if the object is null
or conversion fails.
mirroring the same static method in the ConvertObject, providing alternative easy less code usage options.
- 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 conversion to DateTime fails (e.g., invalid format), logs an error and returns
null
.
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, otherwise null
.
Example usage:
final object1 = '2023-06-26T12:00:00Z';
final dateTime1 = tryToDateTime(object1); // 2023-06-26 12:00:00.000Z
final object2 = DateTime(2023, 6, 26, 12, 0, 0);
final dateTime2 = tryToDateTime(object2); // 2023-06-26 12:00:00.000
final object3 = 'Invalid DateTime';
final dateTime3 = tryToDateTime(object3); // null (logs an error)
final object4 = null;
final dateTime4 = tryToDateTime(object4); // null
Implementation
DateTime? tryToDateTime(
dynamic object, {
dynamic mapKey,
int? listIndex,
String? format,
String? locale,
bool autoDetectFormat = false,
bool useCurrentLocale = false,
bool utc = false,
}) =>
ConvertObject.tryToDateTime(
object,
mapKey: mapKey,
listIndex: listIndex,
format: format,
locale: locale,
autoDetectFormat: autoDetectFormat,
useCurrentLocale: useCurrentLocale,
utc: utc,
);