c# - 比较时间时 DateTimeKind 是否被忽略?

标签 c# .net datetime

var dt1 = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified);
var dt2 = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Local);
var dt3 = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

成对比较的结果让我大吃一惊:

Console.WriteLine(dt1 == dt2); // true
Console.WriteLine(dt1 == dt3); // true
Console.WriteLine(dt2 == dt3); // true

最佳答案

是的,Kind property比较 DateTime 值时会被忽略。

来自 referance source of == operator in DateTime structure :

public static bool operator ==(DateTime d1, DateTime d2)
{
    return d1.InternalTicks == d2.InternalTicks;
}

同样来自 DateTime.Compare documentation 1:

To determine the relationship of t1 to t2, the Compare method compares the Ticks property of t1 and t2 but ignores their Kind property. Before comparing DateTime objects, ensure that the objects represent times in the same time zone.

1: 内部使用==运算符

关于c# - 比较时间时 DateTimeKind 是否被忽略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34807744/

相关文章:

c# - 在 IIS 8 上运行应用程序时如何委派 Windows 身份验证 session ?

.net - 在搜索表单中发布或获取?

mysql - 在Mysql中将周索引转换为日

c# - 从多个 PNG 创建一个 PNG

c# - ReadLine() 与 Read() 有效获取 CR 和 LF?

.net - 任何现有的 IoC 容器都可以动态创建惰性代理类吗?

c# - 将 '\n' 而不是 '\\n' 拆分为字符串数组

javascript - 从忽略时区的 Unix 时间戳创建日期

java - Joda 字符串日期时间到日期时间

c#:使用程序集(通过反射)作为(元)数据存储