hrishi
hrishi

Reputation: 1561

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 times and then compare difference is less than 5 MIN.. Please note I want difference in min. using c#.net

Upvotes: 15

Views: 7904

Answers (3)

Thomas Levesque
Thomas Levesque

Reputation: 292405

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
}

Upvotes: 33

Joel Etherton
Joel Etherton

Reputation: 37533

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.

Upvotes: 0

Oded
Oded

Reputation: 498962

Here is one way of doing it:

 TimeSpan span = firstDate - secondDate;
 return span.TotalMinutes < 5;

Upvotes: 1

Related Questions