tryParseDuration function
Implementation
Duration? tryParseDuration(String? v, [Duration? def]) {
if (v == null || v.isEmpty) return def;
var n = int.tryParse(v);
if (n != null) {
return Duration(milliseconds: n);
}
var s = v.toLowerCase().trim().replaceAll(RegExp(r'\s+'), '');
n = int.tryParse(s.replaceAll(RegExp(r'\D+'), ''));
if (n == null) return def;
if (n == 0) return Duration();
if (s.endsWith("h") ||
s.endsWith("hr") ||
s.endsWith("hs") ||
s.endsWith("hour") ||
s.endsWith("hours")) {
return Duration(hours: n);
} else if (s.endsWith("ms") ||
s.endsWith("milliseconds") ||
s.endsWith("millisecond")) {
return Duration(milliseconds: n);
} else if (s.endsWith("min") ||
s.endsWith("minutes") ||
s.endsWith("minute")) {
return Duration(minutes: n);
} else if (s.endsWith("sec") ||
s.endsWith("seconds") ||
s.endsWith("second") ||
s.endsWith("s")) {
return Duration(seconds: n);
} else {
return def;
}
}