将日期时间与未指定的UTC类型进行比较 [英] Comparing DateTimes with Unspecified and UTC kinds

查看:107
本文介绍了将日期时间与未指定的UTC类型进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个 DateTime 值:



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



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



当比较这两个日期时,两个日期相等。

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

有人可以解释为什么?



对我来说有点奇怪:将date1(这是未指定的类型)转换为UTC时,我清楚地看到日期不同:



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


Yup。这是因为 DateTime 是一个根本破裂的类型,IMO。基本上,在比较中不使用种类。这样做可能会破坏旧的代码,并不总是你想要的。它被添加在.NET 1.1中,并不总是以一个伟大的方式 - 它绝对没有完全集成在你可能预期的每一种方式,如你所看到的比较。



另一个例子,即使是本地(这意味着系统本地时区)对于算术忽略,这意味着调用 AddHours(1)真的只会添加到本地时间,而不是代表已经时间(最终可能是本地时间或当地时间两个小时后,DST转换周期)。



我的建议只是为了避免比较 DateTime 首先不同种类的值。这几乎不是你想要做的。



(当然我也建议使用 Noda Time ,但这是一个稍微不同的事情。)


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

解决方案

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.)

这篇关于将日期时间与未指定的UTC类型进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆