getLocalizedDateTime function
Converts a DateTime or String to a localized DateTime based on the user's timezone.
This function attempts to get the user's timezone from the localization service
and converts the provided dateTime to the appropriate timezone.
Parameters:
dateTime: Either a DateTime object or a String that can be parsed into a DateTime. If it's a String, it should be in a format that DateTime.parse can handle.
Returns: A DateTime object converted to the user's local timezone.
Throws:
- ArgumentError if
dateTimeis neither a DateTime nor a String.
Fallback behavior:
- If the localization service is not available or throws an error, returns the original DateTime.
- If
dateTimeis a String that cannot be parsed, returns the current time. - If
dateTimeis an unsupported type, returns the current time.
Example:
final localTime1 = getLocalizedDateTime(DateTime.now());
final localTime2 = getLocalizedDateTime('2023-12-25T10:30:00Z');
Implementation
DateTime getLocalizedDateTime(Object dateTime) {
try {
// Attempt to get timezone from localization
final localization = Get.find<Localization>();
if (dateTime is DateTime) {
return localization.getTimezoneDateTime(dateTime);
} else if (dateTime is String) {
final parsedDateTime = DateTime.parse(dateTime);
return localization.getTimezoneDateTime(parsedDateTime);
} else {
throw ArgumentError('dateTime must be either DateTime or String');
}
} catch (e) {
// If there's an error, fallback to the original dateTime
if (dateTime is DateTime) {
return dateTime;
} else if (dateTime is String) {
try {
return DateTime.parse(dateTime);
} catch (_) {
return DateTime.now();
}
}
return DateTime.now();
}
}