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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can subtract one
DateTimefrom another to produce aTimeSpanthat represents the time-difference between them. You can then test if the absolute value of this span is within your desired tolerance.The call to
TimeSpan.Duration()can be omitted if you know that the firstDateTimecannot 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 asd1.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)