2

I primarly use Delphi in my workplace and during some thorough unit tests which involved comparing date times I discovered that a direct comparison using the equals operator was not reliable enough when comparing calculated dates etc. So as a rule I started using CompareDateTime and SameDateTime which are built in functions for date comparisons in Delphi.

In C# by force of habit I compare date/times using the standard operators =<>. We have similar functions like DateTime.Compare and DateTime.Equals for date time comparisons therefore in terms of accuracy & reliability should I really be using the built in functions instead?

Will they give me a more accurate comparison that using the operator?

Community
  • 1
  • 1
James
  • 80,725
  • 18
  • 167
  • 237

2 Answers2

4

Given that your date/times are calculated you'd be better off calculating the difference between the times which gives you a TimeSpan.

TimeSpan travelTime = arrival - departure;

You can then check that this is less than your allowed tolerance.

if (Math.Abs(travelTime.TotalMilliseconds) < tolerance)
{
    // times are equal.
}

This similar to the approach you need to take for floating point values, but is independent of that as in this case the inaccuracy stems from your data not how it's represented in memory.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • 1
    This is the first thing that comes to mind for me, too. Could be nicely wrapped up into an extension method on DateTime. – tomfanning Jan 22 '11 at 12:05
  • So what I am confused about is....why allow operator comparisons in the first place if they aren't reliable? What exactly do the operators do under the hood with DateTimes? – James Jan 22 '11 at 12:07
  • @James - They're allowed in the same way that `float1 == float2` is allowed. It's part of the language. If you were dealing with just the date part or *assigned* date/times then the equality would probably be OK, but with calculated times down the millisecond or even second you **have** to have a margin of error. – ChrisF Jan 22 '11 at 12:09
  • I see, so what if dates aren't being calculated but more translated e.g. Local DT to UTC DT using something like `TimeZoneInfo.ConvertDate`, would it be unreliable here to simply compare using operators? – James Jan 22 '11 at 12:20
  • @James - I think the best thing to do there is run some experiments and see what (if any) errors are introduced by the translation process. – ChrisF Jan 22 '11 at 12:24
1

I'm not really sure, but a colleague of mine told me to always use the Equals operator. For DateTime objects, Equals and Compare are comparing the ticks.

If you want to know more about the TimeSpan method ChrisF mentioned, see here.

Community
  • 1
  • 1
Matten
  • 17,365
  • 2
  • 42
  • 64
  • That's ok I know about the `TimeSpan` stuff. Was just looking for clarifiation on if using the operator comparisons are reliable enough. – James Jan 22 '11 at 12:03