找出距离准确的 DateTime 还剩多少天、小时和分钟
Find out how many days, hours and minutes left until exact DateTime
我试图做这样的事情但失败了。我能够编写一天的代码,但不知道还剩下多少小时和分钟。
示例图片:
我为个人项目制作了类似的东西,这是片段。这是一个辅助函数,你必须给它 ms
,EndDateInMs - StartDateInMs
。还有一个 TimeFrame
类型,但你不需要它;只需采用计算 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,
};
}
如果您想将 Duration
转换为天、分钟、小时和秒,您可以这样做:
var days = duration.inDays;
var hours = duration.inHours % 24;
var minutes = duration.inMinutes % 60;
var seconds = duration.inSeconds % 60;
(如果您从总秒数开始,而不是从 Duration
对象开始,您可以先轻松构造一个 Duration
对象:Duration(seconds: totalSeconds)
。 )
请参阅 了解更复杂的版本,它将 Duration
格式化为 1d2h3.45s
.
形式的 String
我试图做这样的事情但失败了。我能够编写一天的代码,但不知道还剩下多少小时和分钟。
示例图片:
我为个人项目制作了类似的东西,这是片段。这是一个辅助函数,你必须给它 ms
,EndDateInMs - StartDateInMs
。还有一个 TimeFrame
类型,但你不需要它;只需采用计算 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,
};
}
如果您想将 Duration
转换为天、分钟、小时和秒,您可以这样做:
var days = duration.inDays;
var hours = duration.inHours % 24;
var minutes = duration.inMinutes % 60;
var seconds = duration.inSeconds % 60;
(如果您从总秒数开始,而不是从 Duration
对象开始,您可以先轻松构造一个 Duration
对象:Duration(seconds: totalSeconds)
。 )
请参阅 了解更复杂的版本,它将 Duration
格式化为 1d2h3.45s
.
String