Tuesday, February 5, 2013

Safely comparing local and universal DateTimes

When you call .Equal or .Compare, internally the value .InternalTicks is compared. This field isunequal, because it has been adjusted a couple of hours to represent the time in the universal time. You should see it this way: the DateTime object represents a time in an unnamed timezone, but not a universal time plus timezone. The timezone is either Local (the timezone of your system) or UTC. You might consider this a lack of the DateTime class.
When converting to another timezone, the time is — and should be — adjusted. This is probably why Microsoft chose to use a method as opposed to a property, to emphasize that an action is taken when converting to UTC.
Originally I wrote here that the structs are compared and the flag for System.DateTime.Kind is different. This is not true: it is the amount of ticks that differs:
t1.Ticks == t2.Ticks;       // false
t1.Ticks.Equals(t2.Ticks);  // false
To safely compare two dates, you could convert them to the same kind. If you convert any date to universal time before comparing you'll get the results you're after:
DateTime t1 = DateTime.Now;
DateTime t2 = t1;
t1.Compare(t1.ToUniversalTime(), t2.ToUniversalTime());  //true
The moral: never compare DateTime naively

0 коммент.:

Post a Comment

Powered by Blogger.