fromDuration static method
Implementation
static TinCanDuration? fromDuration(Duration? duration) {
if (duration == null) {
return null;
}
// 00:00:16.043000
final pattern = RegExp(r'([0-9]+):([0-9]+):([0-9.]+)');
final match = pattern.firstMatch(duration.toString())!;
int inDays = duration.inDays;
int? days = (inDays > 0) ? inDays : null;
int? hours =
(inDays > 0) ? (duration.inHours % 24) : int.tryParse(match.group(1)!);
if (hours == 0) {
hours = null;
}
int? minutes = int.tryParse(match.group(2)!);
double? seconds = double.tryParse(match.group(3)!);
// Truncate (round) to only 0.01 second precision
if (seconds != null) {
seconds = double.parse(seconds.toStringAsFixed(2));
}
final secondsString = (seconds == null)
? null
: ((seconds.toInt() == seconds)
? seconds.toInt().toString()
: seconds.toString());
if (minutes == 0 && seconds == null) {
minutes = null;
}
return TinCanDuration.fromParts(
days: days?.toString(),
hours: hours?.toString(),
minutes: minutes?.toString(),
seconds: secondsString,
);
}