11

I have 2 DateTime values:

date1 <- {15-07-13 20:45:10} with Kind = Unspecified

date2 <- {15-07-13 20:45:10} with Kind = UTC

When comparing these 2 dates, the 2 dates are equal.

if (DateTime.Compare(date1, date2)!=0)
    ...

Can someone can explain why?

A little bit more strange to me: when converting the date1 (which is Unspecified kind) to UTC, I clearly see that the date is different:

date1.ToUniversalTime() --> {15-07-13 18:45:10} with Kind = UTC

4

2 回答 2

18

Does someone can explain me why?

Yup. It's because DateTime is a fundamentally broken type, IMO. Basically the Kind isn't used in comparisons. Doing so would quite possibly have broken old code, and it's not always what you want. It was added on for .NET 1.1, and not always in a great way - it definitely wasn't fully integrated in every way you might have expected, as you've seen for comparisons.

As another example, even for a Kind of Local (which is meant to be the system local time zone) it's ignored for arithmetic, which means a call of AddHours(1) really only adds to the local time, rather than it representing elapsed time (which could end up being the same local time or two hours later in local time, around DST transitions).

My advice is just to avoid comparing DateTime values of different kinds in the first place. It's almost never what you want to do.

(Of course I'd also recommend using Noda Time, but that's a slightly different matter.)

于 2013-07-15T18:57:38.820 回答
13

From the documentation on DateTimeKind (emphasis is mine):

The members of the DateTimeKind enumeration are used in conversion operations between local time and Coordinated Universal Time (UTC), but not in comparison or arithmetic operations.

于 2013-07-15T18:57:21.997 回答