Ted
Ted

Reputation: 113

DateTime timezone in .NET seems to be wrong?

I have been having some fun with DateTime parsing from strings in .NET MVC, and I have identified some curious behaviour. Look at this test:

[Test]
public void DoesItWork()
{
    DateTime theTime = DateTime.Now;
    DateTime theUTCTime = theTime.ToUniversalTime();
    Assert.IsTrue(theTime==theUTCTime);         
}

I'm in the UK right now, and its BST, so I expect the UTC time to be an hour behind the value of DateTime.Now. So it is. But when I call .ToUniversalTime() on my initial date time, as well as subtracting an hour, the value's Kind property is also updated - from Local to Utc. This is also what I would expect.

But when I come to compare the values of these two DateTimevariables, the equality operator doesn't take account of the different Kind values, and simply reports they're different values. To me, this seems flat out wrong.

Can anyone elucidate why it works this way?

Upvotes: 5

Views: 401

Answers (1)

SouXin
SouXin

Reputation: 1564

According to MSDN and MSDN2 when you compare two DateTime values:

Remarks To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind properties.

Remarks The Equality operator determines whether two DateTime values are equal by comparing their number of ticks. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind property.

So it's correct.

Link to DateTime.Kind Property and again from the remark:

The Kind property allows a DateTime value to clearly reflect either Coordinated Universal Time (UTC) or the local time. In contrast, the DateTimeOffset structure can unambiguously reflect any time in any time zone as a single point in time.

UPDATE

Regarding your comment. IMHO it is expected behavior. Because usually, you don't need to compare two DateTimes from different time zone. If you need to do this although, you have to use DateTimeOffset DateTimeOffset Structure which is:

Remarks The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC). Because it exactly defines a date and time relative to UTC, the DateTimeOffset structure does not include a Kind member, as the DateTime structure does. It represents dates and times with values whose UTC ranges from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era), to 11:59:59 P.M., December 31, 9999 A.D. (C.E.).

Upvotes: 4

Related Questions