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.
The Code
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
Calculates the total minutes from the duration.
print(TimeStringHelper.minutesFromTotalSeconds(3661));
// Output: 61
Dart- secondsFromTotalSeconds
Extracts the remaining seconds after minutes are calculated.
print(TimeStringHelper.secondsFromTotalSeconds(3661));
// Output: 1
DartWhy 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