MSDN文档说的很清楚DateTimeKind
使用等式运算符时不会考虑。
Equality 运算符通过比较两个 DateTime 值的刻度数来确定它们是否相等。在比较 DateTime 对象之前,请确保这些对象表示同一时区的时间。您可以通过比较其 Kind 属性的值来做到这一点.
MSDN - DateTime.Equality 运算符 https://msdn.microsoft.com/en-us/library/system.datetime.op_equality(v=vs.110).aspx
您可以编写自己的扩展方法来包含DateTimeKind
比较:
public static bool EqualsWithKind(this DateTime time, DateTime other)
{
return time.Kind == other.Kind &&
time == other;
}
考虑到来自的评论帕纳吉奥蒂斯·卡纳沃斯 and 詹姆斯·索普 about DateTimeOffset
:
如果保证偏移量与本地偏移量相同,则使用。
public static bool EqualsWithTimezone(this DateTime time, DateTime other)
{
return new DateTimeOffset(time) == new DateTimeOffset(other);
}
如果不保证偏移量相同,则使用:
public static bool EqualsInclTimezone(this DateTime time, TimeSpan timeOffset, DateTime other, TimeSpan otherOffset)
{
return new DateTimeOffset(time, timeOffset) == new DateTimeOffset(other, otherOffset);
}