hey guys, I want to calculate the difference between two times and then compare difference is less than 5 MIN.. Please note I want difference in min. using c#.net
views:
98answers:
3
+7
A:
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
}
Thomas Levesque
2010-01-20 14:46:05
Math.Abs(diff.TotalMinutes) would fix the dt1>dt2 problem...
JonB
2010-01-20 15:43:03
yes, good point... fixed
Thomas Levesque
2010-01-20 16:10:08
instead of using Math.Abs, you can also use .Duration() on a timespan like `TimeSpan diff = (dt2 - dt1).Duration();`
Pierre-Alain Vigeant
2010-01-20 16:12:37
I didn't know that method, thanks for the tip... fixed again ;)
Thomas Levesque
2010-01-20 18:01:43
+1
A:
Here is one way of doing it:
TimeSpan span = firstDate - secondDate;
return span.TotalMinutes < 5;
Oded
2010-01-20 14:46:38
This test will return true for "1 hour and 3 minutes"... you have to use TotalMinutes, not Minutes
Thomas Levesque
2010-01-20 14:47:32
@Thomas - yes, I overlooked that portion. Thanks for the correction.
Joel Etherton
2010-01-20 14:57:59
A:
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.
Joel Etherton
2010-01-20 14:53:25
Yah, I wasn't even thinking about that for some reason (it was painfully obvious as soon as you commented on your own answer).
Joel Etherton
2010-01-20 15:01:07