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.
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.
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.
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.
I usally use the TimeSpan.FromXXX methods to do something like this:
if((myDate - myOtherDate) > TimeSpan.FromSeconds(10)) { //Do something here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With