If I try:
DateTime.Now.Subtract(DateTime.UtcNow)
I would expect the result to be very close to zero. But it’s not, instead it’s the time zone difference, in my case, -4 hours. There is a .Kind — the DateTime KNOWS the timezones are different. Why doesn’t it track this for me? Is there a flavor of Subtract that DOES use Kind correctly?
(For reference, a good rundown of what each one outputs can be seen at: https://stackoverflow.com/a/3229429/237091)
Because
DateTimeis fundamentally broken (and there’s more…). IMO it should complain if you try to subtract a value of one kind from another. But no, it just uses the uninterpreted date/time in each value. Very few operations actually take any notice of theKind, unfortunately. (If you useTimeZoneInfo, those operations do take notice of it.)Kindwas hacked into .NET 2.0; before then aDateTimevalue didn’t even know what kind it was – if you used:it would apply the same offset change several times. The BCL team found a couple of spare bits in the binary representation, and used it for
Kind.Basically, I feel your pain. Personally I would prefer it if operations like this threw an exception – subtracting a UTC
DateTimefrom a localDateTimeor vice versa makes little sense, IMO.As an entirely biased plug, you could use Noda Time which separates the ideas of
Instant,LocalDate,LocalTime,LocalDateTime,OffsetDateTimeandZonedDateTime, and doesn’t let you perform non-sensical arithmetic. Our aim is to provide a saner API than the BCL one. That doesn’t necessarily mean we’ve succeeded, of course 🙂