toDateTime property
DateTime?
get
toDateTime
!~~~~~~~~~~~~~~~~~~~~~~~ To Date Time ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Parses a string representation of a date and time into a DateTime object.
This extension method attempts to parse the string as a date and time
using several common formats. It returns null
if the string cannot be
parsed as a valid date and time. It prioritizes parsing using
DateTime.tryParse
for ISO 8601 format, then it attempts parsing
with intl
's DateFormat
for other common formats.
Example:
"2024-03-15 10:30:00".toDateTime; // Returns DateTime(2024, 3, 15, 10, 30, 0)
"2024-03-15".toDateTime; // Returns DateTime(2024, 3, 15, 0, 0, 0)
"15/03/2024".toDateTime; // Returns DateTime(2024, 3, 15, 0, 0, 0)
"March 15, 2024".toDateTime; // Returns DateTime(2024, 3, 15, 0, 0, 0)
"invalid date".toDateTime; // Returns null
null.toDateTime; // Returns null
Returns: A DateTime object if the string can be parsed, or null
otherwise.
Implementation
DateTime? get toDateTime {
final input = this;
return DateTime.tryParse(input) ?? // Try ISO 8601 first
DateFormat('yyyy-MM-dd').tryParse(input) ??
DateFormat('dd/MM/yyyy').tryParse(input) ??
DateFormat('MM/dd/yyyy').tryParse(input) ??
DateFormat('MMM dd, yyyy').tryParse(input) ?? // Example: March 15, 2024
DateFormat('MMMM dd, yyyy').tryParse(input); // Example: March 15, 2024
}