C# 检查两次之间的秒差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8945272/
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
Check difference in seconds between two times
提问by Boardy
Hi all I am currently working on a project where when a certain event happens details about the event including the time that the event occurred is added into a list array.
大家好,我目前正在做一个项目,当某个事件发生时,有关该事件的详细信息(包括事件发生的时间)被添加到列表数组中。
Once the method has finished I then pass on the list to another method that checks its values. Before I go through the loop I check the current time of my PC and I need to check whether the difference between the time saved in the list array and the current time is greater than 5 seconds.
方法完成后,我将列表传递给另一个检查其值的方法。在我进行循环之前,我检查我的 PC 的当前时间,我需要检查保存在列表数组中的时间与当前时间之间的差异是否大于 5 秒。
How would I go about doing this.
我将如何去做这件事。
采纳答案by Jon
Assuming dateTime1and dateTime2are DateTimevalues:
假设dateTime1和dateTime2是DateTime值:
var diffInSeconds = (dateTime1 - dateTime2).TotalSeconds;
In your case, you 'd use DateTime.Nowas one of the values and the time in the list as the other. Be careful of the order, as the result can be negative if dateTime1is earlier than dateTime2.
在您的情况下,您将使用列表DateTime.Now中的一个值和时间作为另一个。注意顺序,因为如果dateTime1早于,结果可能为负dateTime2。
回答by Rich O'Kelly
DateTime has a Subtract methodand an overloaded -operatorfor just such an occasion:
DateTime 有一个Subtract 方法和一个用于这种情况的重载-运算符:
DateTime now = DateTime.UtcNow;
TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
if (difference.TotalSeconds > 5) { ... }
回答by freedeveloper
I use this to avoid negative interval.
我用它来避免负间隔。
var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
回答by stevieg
This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):
此版本始终以正数形式返回秒数差异(与@freedeveloper 的解决方案结果相同):
var seconds = System.Math.Abs((date1 - date2).TotalSeconds);

