Answers:
在这种情况下,DateTime具有一个Subtract方法和一个重载-运算符:
DateTime now = DateTime.UtcNow;
TimeSpan difference = now.Subtract(otherTime); // could also write `now - otherTime`
if (difference.TotalSeconds > 5) { ... }
我用它来避免负间隔。
var seconds = (date1< date2)? (date2- date1).TotalSeconds: (date1 - date2).TotalSeconds;
Math.Abs相反,使用此代码比仅使用上面的答案更具可读性和性能。