Wednesday, November 14, 2007

Comparing DateTime structs ...

Consider the following code:

DateTime localTime = new DateTime(2007, 11, 14, 12, 0, 0, DateTimeKind.Local);
DateTime utcTime = new DateTime(2007, 11, 14, 12, 0, 0, DateTimeKind.Utc);

System.Diagnostics.Debug.Print("Is equal ? {0}", localTime == utcTime);

What do you expect the answer to be?

...and you probably guessed wrong as .NET actually considers them to be equal !?!

MSDN is "somewhat fuzzy" on the subject:

"Calculations and comparisons of DateTime objects are only meaningful if the objects represent times in the same time zone. For that reason, if no time zone is specified for the objects, it is assumed that the developer has some external mechanism, such as an explicit variable or policy, that can be used to determine the time zone in which a DateTime object was created."

No comments: