Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two datetimes

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?

like image 444
Jonas Avatar asked Oct 16 '10 14:10

Jonas


2 Answers

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):

  • 0 if they represent the same point in time (d1.Equals(d2) , d1 == d2). Do note though, that the resolution of DateTime is 1 tick = 100 nanoseconds = 10 ^ -7 seconds.
  • A value greater than 0 if d1 is chronologically after d2 (d1 > d2)
  • A value less than 0 if d1 is chronologically before d2 (d1 < d2)
like image 85
Ani Avatar answered Oct 10 '22 17:10

Ani


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.

like image 41
Adam Lear Avatar answered Oct 10 '22 19:10

Adam Lear