Sometimes we need day, hour, minute, second to countdown, but what we know just second.

For example:

  • 1s -> 0day 0hour 0minute 1s
  • 10s -> 0day 0hour 0minute 10s
  • 100s -> 0day 0hour 1minute 40s

Here is my solution:

void _test() {
  var diffseconds = 100;

  var seconds = diffseconds % 60;
  var minute = diffseconds ~/ 60 % 60;
  var hour = diffseconds ~/ 60 ~/ 60 % 24;
  var day = diffseconds ~/ 60 ~/ 60 ~/ 24;

  print('day=$day');
  print('hour=$hour');
  print('minute=$minute');
  print('second=$seconds');
}

If I can change second to DateTime, I can get day easily with date.day and so on and I don't need to calculate anymore.

So I wonder is there any api or simple way to achieve it without any calculate.

I wonder better solution.


Solution 1: hkh12

Just use Duration(seconds: seconds), it handles values more than 60.

Duration(seconds: 123) // 2 minutes and 3 seconds


Solution 2: julemand101

I don't think this functionality is built into Dart but you can somewhat easy add the following extension to Duration which are more or less what you are already are doing:

extension RestTimeOnDuration on Duration {
  int get inDaysRest => inDays;
  int get inHoursRest => inHours - (inDays * 24);
  int get inMinutesRest => inMinutes - (inHours * 60);
  int get inSecondsRest => inSeconds - (inMinutes * 60);
  int get inMillisecondsRest => inMilliseconds - (inSeconds * 1000);
  int get inMicrosecondsRest => inMicroseconds - (inMilliseconds * 1000);
}

void main() {
  const duration = Duration(seconds: 123);
  print('Days: ${duration.inDaysRest}'); // 0
  print('Hours: ${duration.inHoursRest}'); // 0
  print('Minutes: ${duration.inMinutesRest}'); // 2
  print('Seconds: ${duration.inSecondsRest}'); // 3
  print('Milliseconds: ${duration.inMillisecondsRest}'); // 0
  print('Microseconds: ${duration.inMicrosecondsRest}'); // 0
}