How to compare two times

I wonder how to compare two DateTime objects in .NET using DateTime methods Compare, CompareToor Equalswithout comparing ticks.

I only need a tolerance level in milliseconds or seconds.

How can I do that?

+5
source share
4 answers

You can subtract one DateTimefrom the other to create TimeSpanone that represents the time difference between the two. You can then check if the absolute value of this range is within your desired tolerance.

bool dtsWithinASecOfEachOther = d1.Subtract(d2).Duration() <= TimeSpan.FromSeconds(1);

TimeSpan.Duration() , , DateTime , , .. d1 >= d2.

, DateTime.Compare(d1, d2) , d1.CompareTo(d2):

  • 0, (d1.Equals(d2), d1 == d2). , DateTime 1 tick = 100 = 10 ^ -7 .
  • 0, d1 d2 (d1 > d2)
  • 0, d1 d2 (d1 < d2)
+9

TimeSpan - TimeSpan - , DateTimes:

TimeSpan tolerance = new TimeSpan(0,0,1);
return (date1 - date2) <= tolerance;

Compare, CompareTo Equals , .

- DateTime , :

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);
+2

, , , , , DateTime.Compare(). DateTime.Equals(). , , , TimeSpan:

// For seconds
if (laterDate-earlierDate<=TimeSpan.FromSeconds(1))
  ...

// For milliseconds
if (laterDate-earlierDate<=TimeSpan.FromMilliseconds(1))
  ...
+2

DateTimes . , , , .

+2

All Articles