Dart - Convert Seconds To Minutes, Hours, Days Examples

This tutorial shows you how to convert seconds to minutes, hours, and days in Dart.

If you have a time duration value in seconds and you want to convert it to minutes, hours, or days, it can be done easily in Dart. This tutorial has examples of how to do it.

Convert Using Duration

An easy way to convert a second value is by using Dart's Duration. What you need to do is create an instance of Duration by passing the value to be converted as the seconds named argument. From a Duration instance, you can get the other time units by accessing the properties. It has inDays, inHours, inMinutes, inSeconds, inMilliseconds, and inMicroseconds properties. All of those mentioned properties have integer type.

  final duration = Duration(seconds: 172800);
  print('Duration in minutes: ${duration.inMinutes}');
  print('Duration in hours: ${duration.inHours}');
  print('Duration in days: ${duration.inDays}');

Convert Using Calculation

Using the solution above, you can only get the value as an integer. That means you may get 0 if the converted value is less than 1. If you want to get the result as a double, you can perform division operation to the second value. To convert a second value to a minute value, divide it with 60. To convert a second value to an hour value, divide it with 3600 (60 * 60). To convert a second value to an day value, divide it with 86400 (24 * 60 * 60).

  const secondsPerMinute = 60;
  const secondsPerHour = 60 * 60;
  const secondsPerDay = 24 * 60 * 60;
  final seconds = 1000;
  print('Duration in minutes: ${seconds/secondsPerMinute}');
  print('Duration in hours: ${seconds/secondsPerHour}');
  print('Duration in days: ${seconds/secondsPerDay}');

If you need to round the result to N decimal places, you can read our tutorial about how to round double to N decimal places in Dart.

Summary

Converting a value in seconds to minutes, hours, or days can be done by using Dart's Duration class, which has properties in those time units. However, you can only get the values as integers. If you need to get the values in double, you can perform simple arithmetic operations.

You can also read about: