duration method
String
duration(
- Duration duration, {
- bool round = true,
- bool omitZeros = true,
- bool includeWeeks = false,
- Abbreviation form = Abbreviation.none,
- String? delimiter,
- DurationFormat format = DurationFormat.auto,
- bool dropPrefixOrSuffix = false,
inherited
This will return precise durations. For imprecise durations, use relative()
e.g.:
- 2 minutes 39 seconds
- 2m39s
Params:
format
- format to display the duration. For example, when set toDurationFormat.md
, will result to "3 months 2 days"delimiter
- string to join duration when there are more than one. Defaults to space. For example,form
- Unit string form. For example, minute would look like "18 minutes", "18 min", "18m" in full, mid, short forms, respectively.round
- rounds the smallest unit if set true. If false, truncates. Defaults to true.omitZeros
- unit will be omitted if equal to zero. For example,DurationFormat.md
may return "3 months", but not "3 months 0 days"includeWeeks
- Whetherweek
should be treated as duration unit. Only applicable when using DurationFormat.autodropPrefixOrSuffix
- Whether to drop suffix/prefix. For example, "3h 2m ago" => "3h 2m", "in 7 days" => "7 days"
Implementation
@override
String duration(
Duration duration, {
bool round = true,
bool omitZeros = true,
bool includeWeeks = false,
Abbreviation form = Abbreviation.none,
String? delimiter,
DurationFormat format = DurationFormat.auto,
bool dropPrefixOrSuffix = false,
}) {
final bool past = duration.isNegative;
Duration left = duration.abs();
if (format.isAuto) {
format = DurationFormat.resolveAuto(duration, includeWeeks);
}
final List<String> result = [];
for (int i = 0; i < format.length; i++) {
final bool last = i == format.length - 1;
final DurationUnit unit = format.units[i];
final int unitValue = last
? (_roundOrTruncate(left.inMicroseconds / unit.microseconds, round))
: (left.inMicroseconds ~/ unit.microseconds);
final DurationInterval interval =
DurationInterval.findByUnit(unitValue, unit);
final UnitString? unitString = units[interval];
if (unitString == null) {
throw MomentException(
"UnitString implementation is missing for $interval in localization $locale");
}
if (!(omitZeros && unitValue == 0)) {
result.add(unitString
.get(form, dropPrefixOrSuffix)
.replaceAll(srDelta, unitValue.toString()));
}
left -= Duration(microseconds: unit.microseconds * unitValue);
}
late final String value;
if (result.isEmpty) {
final UnitString? unitString = units[DurationInterval.lessThanASecond];
if (unitString == null) {
throw MomentException(
"UnitString implementation is missing for ${DurationInterval.lessThanASecond} in localization $locale");
}
value = unitString.get(form, dropPrefixOrSuffix);
} else {
value = result.join(delimiter ?? durationDelimiter[form]!);
}
if (dropPrefixOrSuffix) return value;
return past ? relativePast(value) : relativeFuture(value);
}