开发者

How can I compare 2 dates in a Where statement while using NoRM for MongoDB on C#?

开发者 https://www.devze.com 2023-04-02 10:54 出处:网络
I have a table in Mongo. O开发者_StackOverflow社区ne of the fields is a DateTime. I would like to be able to get all of the records that are only for a single day (i.e. 9/3/2011).

I have a table in Mongo. O开发者_StackOverflow社区ne of the fields is a DateTime. I would like to be able to get all of the records that are only for a single day (i.e. 9/3/2011).

If I do something like this:

 var list = (from c in col
             where c.PublishDate == DateTime.Now
             select c).ToList();

Then it doesn't work because it is using the time in the comparison. Normally I would just compare the ToShortDateString() but NoRM does not allow me to use this.

Thoughts?

David


The best way to handle this is normally to calculate the start datetime and end datetime for the date in question and then query for values in that range.

var start = DateTime.Now.Date;
var end = start.AddDays(1);
...

But you'd also be well advised to switch to the official C# driver now. You should also use UTC datetimes in your database (but that gets more complicated).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号