tryLocalizeDuration function

String? tryLocalizeDuration(
  1. int? seconds
)

Parses the given int as a duration of seconds and returns a localized string representing the duration.

Returns null if the given int is null or zero.

Implementation

String? tryLocalizeDuration(int? seconds) {
  if (seconds == null) return null;

  final days = seconds ~/ Duration.secondsPerDay;
  seconds -= days * Duration.secondsPerDay;

  final hours = seconds ~/ Duration.secondsPerHour;
  seconds -= hours * Duration.secondsPerHour;

  final minutes = seconds ~/ Duration.secondsPerMinute;
  seconds -= minutes * Duration.secondsPerMinute;

  final result = [
    if (days > 0) '${days}day',
    if (hours > 0) '${hours}hr',
    if (minutes > 0) '${minutes}min',
  ].join(' ');

  if (result.trim().isEmpty) return null;

  return result;
}