比较相等的日期时间返回false [英] Comparing equal datetimes returns false

查看:217
本文介绍了比较相等的日期时间返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,询问如何比较/存储C#中的日期时间。请考虑以下代码:

I have a query with how datetimes are compared/stored in C#. Consider the following code:

var createdDate = DateTime.Now;
using (cr = new LanguageDictionaryRepository(ds)) {
    cr.Add(new Sybrin10.Data.DTO.LanguageDictionary() {
        Active = true,
        CreatedDate = createdDate,
        CultureCode = cultureCode,
        Data = new System.Text.UTF8Encoding().GetBytes("Test")
    });
    cr.Save();

    var y = cr.FindBy(x => x.CultureCode == cultureCode && x.CreatedDate == createdDate).FirstOrDefault();
    Assert.IsNotNull(y);

Assert.IsNotNull 失败是因为日期时间检查。我希望在创建LanguageDictionary实例时使用变量的值,使两者相等。这是使用Telerik.OpenAccess和MSSQL作为数据库层,因此我假设问题出在那儿。谁能告诉我我是否缺少任何内容以及如何正确比较这些值。

The Assert.IsNotNull is failing because of the datetime check. I would expect that as the LanguageDictionary instance is created with the variable's value that the two would be equal. This is using Telerik.OpenAccess and MSSQL as a DB layer so I'm assuming the problem comes in there. Can anyone tell me if there is anything I'm missing with this and how to correctly compare these values.

编辑:刻度值不同,但我不知道为什么它们都来自我只分配一次的同一变量。

The tick values are different but I don't know why as they both come from the same variable which I only assign to once.

推荐答案

尝试使用 DateTime .quals(x.CreatedDate,createdDate),可能会有所帮助。

Try using DateTime.Equals(x.CreatedDate, createdDate), it might help.

除此之外,正确的 DateTime 比较是一个非常复杂的主题,包含时区,偏移量,utc,本地时间和没什么。在两个看似相同的日期之间进行简单的 == 比较,我就不会感到惊讶。

Other than that, proper DateTime comparing is a massively complicated subject with timezones, offsets, utc, local time and whatnot. I wouldn't at all be suprised at a simple == compare between two seemingly identical dates to return false.

如果 Ticks 的值在写入和读取上不同,则您可能会遇到 DateTimeKind 的问题,将 DateTimeKind.Local 写入数据库,但又返回了 DateTimeKind.Unspecified

If the Ticks value differs on write and read, you're might be facing a DateTimeKind problem, where you're writing a DateTimeKind.Local to the database, but getting back an DateTimeKind.Unspecified.

另一个选择可能是(如果差异很小)数据库中的 DateTime 字段不是足以存储与.net DateTime 相同的毫秒数:

The other option could be (if the difference is small enough) that the DateTime field in your database is not significant enough to store the same amount of milliseconds as the .net DateTime:


单个刻度表示一百纳秒或十分之一秒。毫秒内有10,000个滴答声。

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

取决于您的数据存储,它可能不会像下面这样详细。您的 DateTime 值不是来自同一来源,一个是从内存中读取的,另一个是从数据库中读取的。

Depending on your data storage, it might not be as detailed as this. Your DateTime values do not come from the same source, one is read from memory, the other is read from database.

这篇关于比较相等的日期时间返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆