安全比较本地和通用DateTime是否 [英] Safely comparing local and universal DateTimes

查看:135
本文介绍了安全比较本地和通用DateTime是否的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只注意到什么,似乎像一个荒谬的缺陷与日期时间的比较。

I just noticed what seems like a ridiculous flaw with DateTime comparison.

DateTime d = DateTime.Now;
DateTime dUtc = d.ToUniversalTime();

d == dUtc; // false
d.Equals(dUtc); //false
DateTime.Compare(d, dUtc) == 0; // false

看来,在所有DateTime对象比较操作不能做任何类型的智能转换,如果一个是DateTimeKind.Local,一个是DateTimeKind.UTC。是一个更好的办法来可靠地除了总是UTC时间转换既参与比较比较DateTime是否?

It appears that all comparison operations on DateTimes fail to do any type of smart conversion if one is DateTimeKind.Local and one is DateTimeKind.UTC. Is the a better way to reliably compare DateTimes aside from always converting both involved in the comparison to utc time?

推荐答案

主编,我原来的答案是部分不正确:

Edited, my original answer was partially incorrect:

当你调用 .Equal .Compare ,内部价值 .InternalTicks 进行比较。这个字段是不等的,因为它已被调整了几个小时来重新present时在通用时间。你应该这样看问题:DateTime对象重新presents一个的时间的中一位不愿透露姓名的时区,但不是普遍的时间加上时区。该时区或者是本地(你的系统的时区)或UTC。你可能会认为这是一个缺乏DateTime类的。

When you call .Equal or .Compare, internally the value .InternalTicks is compared. This field is unequal, because it has been adjusted a couple of hours to represent the time in the universal time. You should see it this way: the DateTime object represents a time in an unnamed timezone, but not a universal time plus timezone. The timezone is either Local (the timezone of your system) or UTC. You might consider this a lack of the DateTime class.

转换的另一个时区,时间是—而且应该是—调整。这可能是为什么微软选择使用的方法的,而不是一个属性,以转换为UTC时强调,正在采取的行动。

When converting to another timezone, the time is — and should be — adjusted. This is probably why Microsoft chose to use a method as opposed to a property, to emphasize that an action is taken when converting to UTC.

本来我写到这里的结构进行了比较和标志 System.DateTime.Kind 是不同的。这是不正确的:它是蜱是不同的量:

Originally I wrote here that the structs are compared and the flag for System.DateTime.Kind is different. This is not true: it is the amount of ticks that differs:

t1.Ticks == t2.Ticks;       // false
t1.Ticks.Equals(t2.Ticks);  // false

要安全地比较两个日期,你可以将其转换为同一类。如果转换的任何日期通用时间比较,你会得到你的结果前后:

To safely compare two dates, you could convert them to the same kind. If you convert any date to universal time before comparing you'll get the results you're after:

DateTime t1 = DateTime.Now;
DateTime t2 = t1;
t1.Compare(t1.ToUniversalTime(), t2.ToUniversalTime());  //true

的寓意:根本不比较的DateTime 天真地

The moral: never compare DateTime naively

这篇关于安全比较本地和通用DateTime是否的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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