C# - 以分钟为单位计算时差
C# - Calculating time difference in minutes
我得到了以下代码:
DateTime start = DateTime.Now;
Thread.Sleep(60000);
DateTime end = DateTime.Now;
我想计算开始和结束之间的分钟差。我应该怎么做?对于上面的例子,结果应该是'1'。
提前致谢!
您可以使用 Subtract
方法并使用 TotalMinutes
。
var result = end.Subtract(start).TotalMinutes;
如果您需要它而不需要小数分钟,只需将其转换为 int
。
var result = (int)end.Subtract(start).TotalMinutes;
查看 MSDN 了解更多信息:Substract and TotalMinutes
使用TimeSpan.
它代表一个时间间隔,会为您提供所需的差异。
举个例子。
TimeSpan span = end.Subtract ( start );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
只需取差(如果需要,也可以四舍五入):
double preciseDifference = (end - start).TotalMinutes;
int differentMinutes = (int)preciseDifference;
我认为更优雅的方法是使用秒表-Class
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
我得到了以下代码:
DateTime start = DateTime.Now;
Thread.Sleep(60000);
DateTime end = DateTime.Now;
我想计算开始和结束之间的分钟差。我应该怎么做?对于上面的例子,结果应该是'1'。
提前致谢!
您可以使用 Subtract
方法并使用 TotalMinutes
。
var result = end.Subtract(start).TotalMinutes;
如果您需要它而不需要小数分钟,只需将其转换为 int
。
var result = (int)end.Subtract(start).TotalMinutes;
查看 MSDN 了解更多信息:Substract and TotalMinutes
使用TimeSpan.
它代表一个时间间隔,会为您提供所需的差异。
举个例子。
TimeSpan span = end.Subtract ( start );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
只需取差(如果需要,也可以四舍五入):
double preciseDifference = (end - start).TotalMinutes;
int differentMinutes = (int)preciseDifference;
我认为更优雅的方法是使用秒表-Class
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;