tags:

views:

98

answers:

3

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

+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
Math.Abs(diff.TotalMinutes) would fix the dt1>dt2 problem...
JonB
yes, good point... fixed
Thomas Levesque
instead of using Math.Abs, you can also use .Duration() on a timespan like `TimeSpan diff = (dt2 - dt1).Duration();`
Pierre-Alain Vigeant
I didn't know that method, thanks for the tip... fixed again ;)
Thomas Levesque
+1  A: 

Here is one way of doing it:

 TimeSpan span = firstDate - secondDate;
 return span.TotalMinutes < 5;
Oded
This test will return true for "1 hour and 3 minutes"... you have to use TotalMinutes, not Minutes
Thomas Levesque
Thanks for that, fixed
Oded
@Thomas - yes, I overlooked that portion. Thanks for the correction.
Joel Etherton
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
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