I wonder how to compare two DateTime objects in .NET using DateTime methods Compare
, CompareTo
or Equals
without comparing ticks.
I only need a tolerance level of milliseconds or seconds.
How can this be done?
I wonder how to compare two DateTime objects in .NET using DateTime methods Compare
, CompareTo
or Equals
without comparing ticks.
I only need a tolerance level of milliseconds or seconds.
How can this be done?
You can subtract one DateTime
from another to produce a TimeSpan
that represents the time-difference between them. You can then test if the absolute value of this span is within your desired tolerance.
bool dtsWithinASecOfEachOther = d1.Subtract(d2).Duration() <= TimeSpan.FromSeconds(1);
The call to TimeSpan.Duration()
can be omitted if you know that the first DateTime
cannot represent an earlier point in time than the other, i.e. d1 >= d2
.
To answer your query about the comparison methods,
DateTime.Compare(d1, d2)
produces the same result as d1.CompareTo(d2)
:
d1.Equals(d2)
, d1 == d2
). Do note though, that the resolution of DateTime is 1 tick = 100 nanoseconds = 10 ^ -7 seconds.d1 > d2
)d1 < d2
)Use TimeSpan
for your tolerance check - TimeSpan
is the type returned from subtracting DateTimes:
TimeSpan tolerance = new TimeSpan(0,0,1);
return (date1 - date2) <= tolerance;
Compare
, CompareTo
and Equals
will not take a tolerance for the comparison, so cannot used this way.
Other options are to create new DateTime
s from the existing ones, discarding the unwanted accuracy and comparing the new ones:
DateTime noSeconds1 = new DateTime(d1.Year, d1.Month, d1.Day, d1.Hour, d1.Minute, 0);
DateTime noSeconds2 = new DateTime(d2.Year, d2.Month, d2.Day, d2.Hour, d2.Minute, 0);
noSeconds1.Equals(noSeconds2);
DateTime.Compare(noSeconds1, noSeconds2);
noSeconds1.CompareTo(noSeconds2);
Generally, if you want a single compare to tell you which date is less, equal to or greater, use DateTime.Compare(). Otherwise, you can use DateTime.Equals(). To add a tolerance value, subtract one from the other and compare result to be less than some TimeSpan:
// For seconds
if (laterDate-earlierDate<=TimeSpan.FromSeconds(1))
...
// For milliseconds
if (laterDate-earlierDate<=TimeSpan.FromMilliseconds(1))
...
You could convert both DateTimes to string and compare the resulting strings. Make sure you define the string format to avoid problems on machines with different regional settings than yours.