考虑以下(简化的)代码:
DateTime now = DateTime.Now;
DateTime now2 = new DateTime(now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second,
now.Millisecond, now.Kind);
bool condition = (now <= now2);
由于我已将 now
的字段复制到 now2
,因此 DateTime
结构的这两个实例应该相等。但是,condition
的计算结果为 false
。为什么?
有什么方法可以更改代码以使条件计算为真吗?
最佳答案
It's the Ticks .它总是蜱虫。有时。
DateTime now = DateTime.Now;
DateTime now2 = new DateTime(now.Year, now.Month, now.Day,
now.Hour, now.Minute, now.Second, now.Millisecond);
bool condition = (now <= now2);
var diff = now2 - now;
时间分辨率小于毫秒。 Ticks
is the real value :
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar), which represents DateTime.MinValue.
它有一个构造函数:
var reallyNow = new Datetime(now.Ticks);
您从未将 Ticks
的任何值传递给 now2
的构造函数(因为它没有参数),所以 now2.Ticks
末尾将有四个零。但是,您直接复制到 now
的 DateTime.Now
确实有一个不能被 10,000 整除的 Ticks
值。
关于c# - 为什么这两个 DateTime 实例不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655914/