c# - DateTime 比较忽略类型?

标签 c# datetime utc

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

这对我来说看起来像是一个错误,如果不是的话color me surprised .

每次比较我都必须调用 ToUniversalTime() 还是有更好的选择?

您如何避免诸如忘记调用 ToUniversalTime() 或由于 DateTimeKind.Unspecified 而得到错误结果之类的陷阱?

最佳答案

MSDN 文档非常清楚,DateTimeKind 未考虑使用 Equality 运算符。

The Equality operator determines whether two DateTime values are equal by comparing their number of ticks. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind property.

MSDN - DateTime.Equality Operator

您可以编写自己的扩展方法以包含 DateTimeKind 比较:

public static bool EqualsWithKind(this DateTime time, DateTime other)
{
      return time.Kind == other.Kind &&
             time == other;
}

考虑到 Panagiotis KanavosJames Thorpe 关于 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);
}

关于c# - DateTime 比较忽略类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28602941/

相关文章:

python - 在Python中将datetime.date转换为UTC时间戳

c# - 数据绑定(bind)后如何添加项目?

c# - 在 C#.NET 中设置 NTFS 权限

c# - DateTime.ParseExact - 为什么 yy 变成 2015 而不是 1915

.Net DateTime 到 DOS 日期 32 位转换

timezone - 使用moment.js将跨越Fall DST边界的一系列非UTC时间戳转换为UTC时间戳的正确方法?

c# - 使用 HtmlAgilityPack 解析未从网页关闭的标签

MySQL TIMESTAMP 停止处理夏令时转换

datetime - 程序集 A86 - 获取并显示时间

mysql - JDBC/MySQL : Save timestamp always using UTC