Hi I want to tryParse
multiple date formats. tryParse
method is available in DateTime
but not in DateFormat
. I want to use DateFormat
as I want to parse multiple format. If I use Parse
method then I have to use a try catch
block.
Currently I am parsing a single date format below. For parsing another date format I have to add it in the catch block.
try {
print(DateFormat('MM/dd/yyyy').parse(line.text));
scannedString = line.text;
} catch (e) {
// parse another date format
}
I am searching for a more convenient way for parsing multiple date formats. Feel free to share your insights and I plan to share if I find any. Thanks for reading!
CodePudding user response:
If you want, you can easily add your own tryParse
function or extension method that operates on a DateFormat
:
extension DateFormatTryParse on DateFormat {
DateTime? tryParse(String inputString, [bool utc = false]) {
try {
return parse(inputString, utc);
} on FormatException {
return null;
}
}
}
If you have a number of different formats that you'd like to try, you also could process them in a loop:
/// Attempts to parse a [String] to a [DateTime].
///
/// Attempts to parse [dateTimeString] using each [DateFormat] in [formats].
/// If none of them match, falls back to parsing [dateTimeString] with
/// [DateTime.tryParse].
///
/// Returns `null` if [dateTimeString] could not be parsed.
DateTime? tryParse(
Iterable<DateFormat> formats,
String dateTimeString, {
bool utc = false,
}) {
for (var format in formats) {
try {
return format.parse(dateTimeString, utc);
} on FormatException {
// Ignore.
}
}
return DateTime.tryParse(dateTimeString);
}