英文:
How can I convert a time difference in MillisecondsSinceEpoch back to minutes in dart/flutter
问题
我有一个屏幕显示从开始到结束的持续时间百分比。开始和结束时间是从TimeOfDay获取的,我已经添加了日期以生成一个DateTime.millisecondsSinceEpoch整数。
现在我可以通过简单的减法找到开始和结束之间的时间差。我如何将得到的值更改为分钟以计算百分比。当我将其转换回日期时,输出不是时间差,而是一个新的日期。
int trainingStartInEpoch = DateTime(trainingDateYear, trainingDateMonth, trainingDateDay, trainingStartHour, trainingStartMinutes).millisecondsSinceEpoch;
int trainingEndInEpoch = DateTime(trainingDateYear, trainingDateMonth, trainingDateDay, trainingEndHour, trainingEndMinutes).millisecondsSinceEpoch;
int timeDiff = trainingEndInEpoch - trainingStartInEpoch;
final int minutesDifference = timeDiff ~/ (60 * 1000); // Convert milliseconds to minutes
print("epochDiff if positive $timeDiff");
print("minutesDifference if positive $minutesDifference");
英文:
I have a screen that shows the percentage of a duration from start to finish. The start and end time was get from TimeOfDay and I have added the date to generate a DateTime.millisecondsSinceEpoch integer.
Now I can find the time difference between the start and end by simple subtraction. How can I change the value I get to a minute to calculate the percentage. When I convert it back to date; the output is not the time difference, it is a new date.
int trainingStartInEpoch = DateTime(trainingDateYear, trainingDateMonth, trainingDateDay, trainingStartHour, trainingStartMinutes).millisecondsSinceEpoch;
int trainingEndInEpoch = DateTime(trainingDateYear, trainingDateMonth, trainingDateDay, trainingEndHour, trainingEndMinutes).millisecondsSinceEpoch;
int timeDiff = trainingEndInEpoch - trainingStartInEpoch;
final DateTime date2 = DateTime.fromMillisecondsSinceEpoch(timeDiff);
print("epochDiff if posetive" " $timeDiff");
print("difDate if posetive" " $date2");
Below is the output
epochDiff if posetive 14400000
difDate if posetive 1970-01-01 07:00:00.000
答案1
得分: 0
一个简单的方法是使用DateTime
中的.difference()
函数。例如:
final DateTime startTime = ...;
final DateTime endTime = ...;
final Duration duration = endTime.difference(startTime);
print("持续时间为 ${duration.inMinutes} 分钟");
// duration.inMinutes
// duration.inSeconds
// duration.inDays 等等
您可以使用.inMinutes
属性获取总持续时间(以分钟为单位),还可以获取秒、小时、天等等。
英文:
A simple approach would be using the .difference()
function in DateTime
. For example:
final DateTime startTime = ...;
final DateTime endTime = ...;
final Duration duration = endTime.difference(startTime);
print("The duration is ${duration.inMinutes} minute(s)");
// duration.inMinutes
// duration.inSeconds
// duration.inDays etc.
You can get the total duration in minutes by using the .inMinutes
attribute, you can also get the seconds, hours, days and etc.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论