gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:49 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com