Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 711
dthrasher Avatar asked Dec 19 '08 16:12

dthrasher


People also ask

Can datetime objects be compared?

To compare datetime objects, you can use comparison operators like greater than, less than or equal to. Like any other comparison operation, a boolean value is returned.

How do you compare dates?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

Can you compare datetime Python?

Use the datetime Module and the < / > Operator to Compare Two Dates in Python. datetime and simple comparison operators < or > can be used to compare two dates. The datetime module provides the timedelta method to manipulate dates and times.


1 Answers

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

if((myDate - myOtherDate) > TimeSpan.FromSeconds(10)) {    //Do something here } 
like image 111
Micah Avatar answered Oct 04 '22 02:10

Micah