How do you compare DateTime objects using a specified tolerance in C#?

dthrasher picture dthrasher · Dec 19, 2008 · Viewed 17.9k times · Source

By default C# compares DateTime objects to the 100ns tick. However, my database returns DateTime values to the nearest millisecond. What's the best way to compare two DateTime objects in C# using a specified tolerance?

Edit: I'm dealing with a truncation issue, not a rounding issue. As Joe points out below, a rounding issue would introduce new questions.

The solution that works for me is a combination of those below.

(dateTime1 - dateTime2).Duration() < TimeSpan.FromMilliseconds(1)

This returns true if the difference is less than one millisecond. The call to Duration() is important in order to get the absolute value of the difference between the two dates.

Answer

Micah picture Micah · Dec 19, 2008

I usally use the TimeSpan.FromXXX methods to do something like this:

if((myDate - myOtherDate) > TimeSpan.FromSeconds(10))
{
   //Do something here
}