Calculating the difference between 2 times, and then compare the difference to see if it is less than 5 minutes
I want to calculate the difference between two time开发者_JS百科s and then compare difference is less than 5 MIN.. Please note I want difference in min. using c#.net
Just use the subtraction operator, and use the Duration
method to get the absolute value
DateTime dt1 = ...;
DateTime dt2 = ...;
TimeSpan diff = (dt2 - dt1).Duration();
if (diff.TotalMinutes < 5)
{
// do something
}
Here is one way of doing it:
TimeSpan span = firstDate - secondDate;
return span.TotalMinutes < 5;
Almost identical to @Thomas, but another method -
Assuming that dt1 is greater than dt2
if(dt1.Sutract(dt2).TotalMinutes < 5)
{
// do
}
The primary difference is that it uses the dt1 memory space to perform the subtraction.
Edit: To use the TotalMinutes correction. The substract method is still present in the datetime object though so I'll leave it here.
精彩评论