DateTime比较忽略类型吗? [英] DateTime Compare Ignores Kind?
问题描述
DateTime d1=new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime d2=new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Local);
Console.WriteLine(d1==d2); // prints true
Console.WriteLine(d1<d2); // prints false
Console.WriteLine(d1.CompareTo(d2)); // prints 0
Console.WriteLine(d1.ToUniversalTime()==d2.ToUniversalTime()); // prints false
对我来说,这似乎是个错误,如果不是让我惊讶的话.
This looks like a bug to me, if not color me surprised.
对于每个比较,我都必须调用ToUniversalTime()还是有更好的选择?
Do I have to call ToUniversalTime() for every comparison or is there a better alternative?
如何避免由于诸如DateTimeKind.Unspecified而忘记调用ToUniversalTime()或得到错误结果的陷阱?
How do you avoid pitfalls like forgetting to call ToUniversalTime() or getting a wrong result because of DateTimeKind.Unspecified?
推荐答案
MSDN文档非常清楚,没有使用Equality运算符将 DateTimeKind
考虑在内.
The MSDN documentation is quite clear that DateTimeKind
is not taken into account using the Equality operator.
Equality运算符通过比较两个滴答数来确定两个DateTime值是否相等.在比较DateTime对象之前,请确保这些对象表示同一时区中的时间.您可以通过比较其Kind属性的值来完成此操作.
您可以编写自己的扩展方法以包括 DateTimeKind
比较:
You could write your own extension method to include the DateTimeKind
comparison:
public static bool EqualsWithKind(this DateTime time, DateTime other)
{
return time.Kind == other.Kind &&
time == other;
}
考虑到 Panagiotis Kanavos 和 James Thorpe 关于 DateTimeOffset
的评论:
在保证偏移量与本地偏移量相同的情况下使用.
Use if the offsets are guaranteed to be the same as the local offset.
public static bool EqualsWithTimezone(this DateTime time, DateTime other)
{
return new DateTimeOffset(time) == new DateTimeOffset(other);
}
如果偏移量不能保证相同,则使用:
Use if the offsets are NOT guaranteed to be the same:
public static bool EqualsInclTimezone(this DateTime time, TimeSpan timeOffset, DateTime other, TimeSpan otherOffset)
{
return new DateTimeOffset(time, timeOffset) == new DateTimeOffset(other, otherOffset);
}
这篇关于DateTime比较忽略类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!