As the title says, I got a string '01:23.290', it looks like a Duration, but not. Now I need to use this to compare with a real Duration, and I don't how to deal with it. Is there any methods?
3 Answers
Use a parsing function like this, then use the comparison methods of Duration
:
Duration parseDuration(String s) {
int hours = 0;
int minutes = 0;
int micros;
List<String> parts = s.split(':');
if (parts.length > 2) {
hours = int.parse(parts[parts.length - 3]);
}
if (parts.length > 1) {
minutes = int.parse(parts[parts.length - 2]);
}
micros = (double.parse(parts[parts.length - 1]) * 1000000).round();
return Duration(hours: hours, minutes: minutes, microseconds: micros);
}
Package duration
provides functions parseTime
and tryParseTime
to parse duration strings obtained by Duration().toString()
.
Usage is straight forward:
print(parseTime(Duration(hours: 5, seconds: 10, milliseconds: 567).toString()));
Another way using DateTime and DateFormat:
Duration durationParse(String time) {
final ts = DateFormat('y-MM-dd').format(DateTime.now());
final dt = DateTime.parse('$ts $time');
return Duration(hours: dt.hour, minutes: dt.minute, seconds: dt.second);
}