Formatting Time in Flutter/Dart: A Simple Helper Class
When working on Flutter projects, you might need to format durations into readable time strings. This could be for timers, media players, or activity trackers. To make this task a bit easier, here’s a lightweight helper class, TimeStringHelper, that handles common formatting needs.
What TimeStringHelper Does
Converts milliseconds into readable time strings.
Formats durations into HH:mm:ss or mm:ss formats.
Provides methods to extract minutes and seconds from a total duration in seconds.
class TimeStringHelper {
static String timeStringFromMilliSeconds(int milliseconds) {
return timeStringFromSeconds((milliseconds / 1000).floor());
}
static String timeStringFromSeconds(int secondsDuration) {
int hours = secondsDuration ~/ 3600;
int minutes = (secondsDuration % 3600) ~/ 60;
int seconds = secondsDuration % 60;
var hoursStr = hours.toString();
var minutesStr = minutes.toString().padLeft(2, '0');
var secondsStr = seconds.toString().padLeft(2, '0');
return hours > 0 ? "$hoursStr:$minutesStr:$secondsStr" : "$minutesStr:$secondsStr";
}
static int minutesFromTotalSeconds(int secondsDuration) {
return secondsDuration ~/ 60;
}
static int secondsFromTotalSeconds(int secondsDuration) {
return secondsDuration % 60;
}
}
DartHow It Works
Here’s a quick breakdown of how the methods in the class work:
- timeStringFromMilliSeconds
Converts milliseconds to seconds and formats the result.
print(TimeStringHelper.timeStringFromMilliSeconds(3661000));
// Output: "1:01:01"
Dart- timeStringFromSeconds
Formats seconds into a readable string. If the duration is an hour or longer, it includes the hours.
print(TimeStringHelper.timeStringFromSeconds(3661));
// Output: "1:01:01"
print(TimeStringHelper.timeStringFromSeconds(61));
// Output: "01:01"
Dart- minutesFromTotalSeconds
This one returns an int. It’s useful if you want to create a duration time picker and need to set it to an initial value. So in my case I have a duration in total seconds and I want to get the minute wheel value from it.
Calculates the total minutes from the duration.
print(TimeStringHelper.minutesFromTotalSeconds(205));
// Output: 3
Dart- secondsFromTotalSeconds
This is the same as the last function, just for the remaining seconds.
Extracts the remaining seconds after minutes are calculated.
print(TimeStringHelper.secondsFromTotalSeconds(205));
// Output: 25
DartThis is my duration picker, where the user can pick a duration in minutes and seconds. I set the initial values using the two last functions.
Why Use This?
This class keeps time formatting simple and reusable. It’s not overly complex, but it can save time when working with durations in different parts of your app.
Leave a Reply