Charles Bretana
Charles Bretana

Reputation: 146449

.Net DateTime bug? Or just poorly designed

This behavior caused me to waste a significant amount of time this past week. Does anyone have an explanation for why this was designed this way ???|
(I am in PST, so the DST Offset is +7 right now)

var utc = new DateTime(2012, 6, 5, 9, 0, 0, DateTimeKind.Utc);  
var lcl = new DateTime(2012, 6, 5, 8, 0, 0, DateTimeKind.Local);  // this is 15:00 Utc
Assert.IsTrue(lcl.ToUniversalTime() > utc);   //  THIS SUCCEEDS  (as it should)
Assert.IsTrue(lcl > utc);                     //  THIS FAILS (with the same times!!!)

This was doubly confusing because in my actual code, the variable that had kind set to to DateTimeKind.Local was originally set with DateTimeKind.Utc (on another machine) but was being evaluated after a network transfer to the machine where the comparison was being made, and had had its kind changed during the transfer (using net.tcp remoting).

Upvotes: 1

Views: 308

Answers (2)

to StackOverflow
to StackOverflow

Reputation: 124696

It's not a bug, it's a "feature".

The DateTime Type does not know about time zones, so there is no sensible way to compare the Kind property (which can be "Unspecified", "Local" or "Utc"). In fact in .NET 1.x it didn't even have a Kind property.

If you need to compare date/time values from different time zones, you need to use a Type that's aware of time zones, such as DateTimeOffset.

Upvotes: 0

jason
jason

Reputation: 241601

It's known, and related to this: http://msmvps.com/blogs/jon_skeet/archive/2012/05/02/more-fun-with-datetime.aspx

Upvotes: 3

Related Questions