DateTime.Compare() 在相​​同的 DateTimes 上返回 1

DateTime.Compare() is returning 1 on identical DateTimes

我一直致力于通过 EntityFramwork 6 获取消息。

基本上我有一个API,我将日期传递给它,然后我使用EntityFramework 来获取最新消息。

现在,当我使用 DateTime.Compare(date1, date2) 时,结果是 1,这是不正确的,因为日期是相同的。

您可以在这张图片中看到:

日期相同但 testd = 1

知道为什么会发生这种情况吗?

代码如下:

var result = ChatProvider
                .GetAllChatsForUser(memberUser.UserName)
                .Where(x => x.FromUser.Equals(lastMessage.FromUser)).OrderBy(x => x.DateTimeCreated).LastOrDefault();

            var testd = DateTime.Compare(result.DateTimeCreated, Date);

谢谢!

Microsoft 的 Reference Source for DateTime.Compare 显示(第 565 行说明)

public static int Compare(DateTime t1, DateTime t2) {
    Int64 ticks1 = t1.InternalTicks;
    Int64 ticks2 = t2.InternalTicks;
    if (ticks1 > ticks2) return 1;
    if (ticks1 < ticks2) return -1;
    return 0;
}

这证实了 Jon Skeet 的假设,即必须存在亚秒级差异。特别是,没有考虑 DateTimeKind 等其他信息。

您可以在与此函数进行比较之前四舍五入到所需的精度(当然这不适用于 EF,必须在客户端完成)。

private DateTime Round(DateTime dt, TimeSpan precision)
{
    return new DateTime(((dt.Ticks + precision.Ticks/2) / precision.Ticks) * precision.Ticks);
}

像这样使用

var oneSecond = TimeSpan.FromSeconds(1);
var testd = DateTime.Compare(
    Round(result.DateTimeCreated, oneSecond),
    Round(Date, oneSecond));