C# 给定两个日期,如何以分钟为单位获得 TimeSpan?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1030869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:33:44  来源:igfitidea点击:

How do I get TimeSpan in minutes given two Dates?

c#

提问by Sreedhar

To get TimeSpan in minutes from given two Dates I am doing the following

要从给定的两个日期在几分钟内获得 TimeSpan,我正在执行以下操作

int totalMinutes = 0;
TimeSpan outresult = end.Subtract(start);
totalMinutes = totalMinutes + ((end.Subtract(start).Days) * 24 * 60) + ((end.Subtract(start).Hours) * 60) +(end.Subtract(start).Minutes);
return totalMinutes;

Is there a better way?

有没有更好的办法?

采纳答案by Josh

TimeSpan span = end-start;
double totalMinutes = span.TotalMinutes;

回答by Anton Gogolev

See TimeSpan.TotalMinutes:

请参阅TimeSpan.TotalMinutes

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

获取以整数和小数分钟表示的当前 TimeSpan 结构的值。

回答by Luke Quinane

I would do it like this:

我会这样做:

int totalMinutes = (int)(end - start).TotalMinutes;

回答by David Bo?jak

Why not just doing it this way?

为什么不这样做呢?

DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;

Hope this helps.

希望这可以帮助。

回答by David Bo?jak

double totalMinutes = (end-start).TotalMinutes;