c# - 为什么这两个 DateTime 实例不同?

标签 c# .net datetime

考虑以下(简化的)代码:

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;

enter image description here

时间分辨率小于毫秒。 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 末尾将有四个零。但是,您直接复制到 nowDateTime.Now 确实有一个不能被 10,000 整除的 Ticks 值。

关于c# - 为什么这两个 DateTime 实例不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655914/

相关文章:

c# - MassTransit RabbitMq 发送消息

c# - 如何使用 gstreamer-sharp 捕获视频帧

c# - 为什么不能在 C# 中进行多重继承?

c# - 如何在 Linux 上使用内置的 Kinect 驱动程序?

c# - 在 Linux 上更改主机名和端口托管 .net 核心 DLL

c# - ReSharper 中可能的空赋值。我看不出那怎么可能为空?

mysql - MySQL 中的添加和删除时间

Javascript new Date() 返回不同的日期

mysql查询查找连续日的日期范围内可供预订的可用汽车

c# - 以编程方式监视在 visual studio 中打开了哪个选项卡