tryParseLoose method
Given user input, attempt to parse the inputString
'loosely' into the
anticipated format, accepting some variations from the strict format.
If inputString
is accepted by tryParseStrict, just return the result. If
not, attempt to parse it, but accepting either upper or lower case,
allowing delimiters to be missing and replaced or supplemented with
whitespace, and allowing arbitrary amounts of whitespace wherever
whitespace is permitted. Note that this does not allow trailing
characters, the way tryParse does. It also does not allow alternative
names for months or weekdays other than those the format knows about. The
restrictions are quite arbitrary and it's not known how well they'll work
for locales that aren't English-like.
If inputString
does not parse, this returns null
.
For example, this will accept
DateFormat.yMMMd('en_US').tryParseLoose('SEp 3 2014');
DateFormat.yMd('en_US').tryParseLoose('09 03/2014');
DateFormat.yMd('en_US').tryParseLoose('09 / 03 / 2014');
It will NOT accept
// 'Sept' is not a valid month name.
DateFormat.yMMMd('en_US').tryParseLoose('Sept 3, 2014');
Implementation
DateTime? tryParseLoose(String inputString, [bool utc = false]) {
try {
return parseLoose(inputString, utc);
} on FormatException {
return null;
}
}