Alex Rivera | Logout

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

Asked 2008-12-19T16:08:50.990
37

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.

Edit
Report

1 Answer

5

You need to remove the milliseconds component from the date object. One way is:

DateTime d = DateTime.Now;
d.Subtract(new TimeSpan(0, 0, 0, 0, d.Millisecond));

You can also subtract two datetimes

d.Subtract(DateTime.Now);

This will return a timespan object which you can use to compare the days, hours, minutes and seconds components to see the difference.

answered 2008-12-19T16:18:03.420

Your Answer