Comparing DateTimes with Unspecified and UTC Types

I have 2 DateTime values:

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

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

When comparing these two dates, 2 dates are equal.

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

Can someone explain why?

A little weirder for me: when converting date1 (which is Unspecified) to UTC, I clearly see that the date is different:

date1.ToUniversalTime () โ†’ {15-07-13 18:45:10} using Kind = UTC

+6
source share
2 answers

Can anyone explain to me why?

Yeah. This is because DateTime is a fundamentally broken type , IMO. Basically Kind not used when comparing. This can break the old code, and this is not always what you want. It was added for .NET 1.1, and not always in great shape - it definitely was not fully integrated in all possible cases, as you saw for comparison.

As another example, even for Kind of Local (which is for the local time zone of the system) it is ignored for arithmetic, which means that the AddHours(1) call really only adds to the local time, instead of representing the elapsed time (which may end in the same local time or two hours later at local time, during the DST transition period).

My advice is to avoid comparing DateTime values โ€‹โ€‹of different kinds. This is almost never what you want to do.

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

+10
source

From the documentation on DateTimeKind (my emphasis):

The members of the DateTimeKind enumeration are used in converting operations between local time and coordinated universal time (UTC) , but not in comparison or arithmetic operations .

+8
source

Source: https://habr.com/ru/post/949493/


All Articles