I tried to do something like this but failed. I was able to code a single day, but not how many hours and minutes are left.
Example picture:
CodePudding user response:
I made something similar for a personal project, this is the snippet. It's a helper function to which you must give ms, being, EndDateInMs - StartDateInMs. There's also a TimeFrame type, but you don't need it; just take the logic for calculating the weeks/days/hours/minutes.
import '../enums/enums.dart';
Map<TimeFrame, int> msConverter(double ms) {
int minutes;
int hours;
int days;
int weeks;
const msInWeek = 6.048e 8;
weeks = (ms / msInWeek).floor();
final msLeftForDays = ms - (msInWeek * weeks);
const msInDay = 8.64e 7;
days = (msLeftForDays / msInDay).floor();
final msLeftForHours = msLeftForDays - (msInDay * days);
const msInHour = 3.6e 6;
hours = (msLeftForHours / msInHour).floor();
final msLeftForMinutes = msLeftForHours - (msInHour * hours);
const msInMinute = 60000;
minutes = (msLeftForMinutes / msInMinute).round();
return <TimeFrame, int>{
TimeFrame.Weeks: weeks,
TimeFrame.Days: days,
TimeFrame.Hours: hours,
TimeFrame.Minutes: minutes,
};
}
CodePudding user response:
If you want to convert a Duration into days, minutes, hours, and seconds, you can just do:
var days = duration.inDays;
var hours = duration.inHours % 24;
var minutes = duration.inMinutes % 60;
var seconds = duration.inSeconds % 60;
(If you're starting from, say, a total number of seconds instead of from a Duration object, you can easily construct a Duration object first: Duration(seconds: totalSeconds).)
See https://stackoverflow.com/a/68685066/ for a more complex version that formats a Duration as a String of the form 1d2h3.45s.
