Comparing equal datetimes not comparing

只谈情不闲聊 提交于 2019-11-30 18:49:55

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

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.

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.

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:

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

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.

SqlServer stores a datetime in (about) 3-millisecond increments.

datetime values are rounded to increments of .000, .003, or .007 seconds

A roundtrip of a DateTime through the database could thus be off by a few ms.

So you should not test for "exactly equal", but for "close enough"

var y = cr.FindBy(x => x.CultureCode == cultureCode && 
                    x.CreatedDate >= createdDate.AddMilliseconds(-5) && 
                    x.CreatedDate <= createdDate.AddMilliseconds(5))
     .FirstOrDefault();

I think it might be better for you to use DateTime.UtcNow when you store the data and then you don't have to worry about daylight saving time issues etc. You can then display it how you want later using the culture you pick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!