toDateTime method
Parameters:
originFormat: Optional. The format string for DateFormat. If null, ISO8601 UTC is assumed.asLocal: Optional. Default true. If true, the resulting DateTime is converted to local time.
Example usage:
Example 1: ISO8601 UTC string, default local conversion
String utcString = "2025-12-13T01:44:43.147498Z";
DateTime? dtLocal = utcString.toDateTime();
print(dtLocal);
-> Output (if timezone UTC+7): 2025-12-13 08:44:43.147498
Example 2: ISO8601 UTC string, keep as UTC
DateTime? dtUtc = utcString.toDateTime(asLocal: false);
print(dtUtc);
-> Output: 2025-12-13 01:44:43.147498Z
Example 3: Custom format string
String dateString = "13/12/2025 01:44";
DateTime? dtCustom = dateString.toDateTime(originFormat: "dd/MM/yyyy HH:mm");
print(dtCustom);
-> Output: 2025-12-13 01:44:00.000
The method will:
- Attempt parsing as ISO8601 (UTC) if
originFormatis null. - If ISO8601 fails, it tries a set of common formats defined in
commonFormats. - Use the
_supportedLocalesfor parsing non-UTC formats to handle locale-specific differences.
Returns null if parsing fails.
Implementation
DateTime? toDateTime({String? originFormat, bool asLocal = true}) {
if (this == null || this!.isEmpty) return null;
DateTime? parsed;
// List of common date/time formats for fallback
final List<String> commonFormats = [
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", // ISO8601 with milliseconds
"yyyy-MM-dd'T'HH:mm:ss'Z'", // ISO8601 without milliseconds
"yyyy-MM-dd HH:mm:ss.SSS", // Database format with milliseconds
"yyyy-MM-dd HH:mm:ss", // Database format without milliseconds
"yyyy/MM/dd HH:mm:ss.SSS",
"yyyy/MM/dd HH:mm:ss",
"dd/MM/yyyy HH:mm:ss",
"MM/dd/yyyy HH:mm:ss",
"dd-MM-yyyy HH:mm:ss",
"MM-dd-yyyy HH:mm:ss",
"dd/MM/yyyy",
"MM/dd/yyyy",
"yyyy-MM-dd",
"yyyy/MM/dd",
"MM-dd-yyyy",
"dd-MM-yyyy",
];
// Attempt parsing using originFormat first, if provided
if (originFormat != null) {
for (final locale in _supportedLocales) {
try {
parsed = DateFormat(originFormat, locale).parseStrict(this!);
break;
} catch (e) {
debugPrint(
'toDateTime parse with format "$originFormat" failed for locale $locale: $e',
);
}
}
} else {
// Attempt ISO8601 parsing first
try {
parsed = DateTime.parse(this!);
} catch (_) {
// Fallback to common formats
for (final format in commonFormats) {
for (final locale in _supportedLocales) {
try {
parsed = DateFormat(format, locale).parseStrict(this!);
break;
} catch (_) {}
}
if (parsed != null) break;
}
}
}
if (parsed == null) return null;
// Convert to local time if requested
return asLocal ? parsed.toLocal() : parsed;
}