Linq select where date is yesterday

本文关键字:is yesterday date where select Linq | 更新日期: 2023-09-27 17:50:12

我已经做到了:

DateTime yesterday = DateTime.Today.AddDays(-1);
YesterdaysRegistrations = db.tblForumAuthors.Where(c => c.Join_date == yesterday).Count();

肯定有昨天加入日期的记录,但这一直返回0 !有人能告诉我我做得对吗?

Linq select where date is yesterday

AddDays保留时/分/秒组件。您要么必须使用(如果c.Join_date只是日期组件):

DateTime yesterday = DateTime.Today.AddDays(-1).Date;

DateTime yesterday = DateTime.Today.AddDays(-1).Date;
DateTime yesterdayEnd = DateTime.Today.Date.AddSeconds(-1);
db.tblForumAuthors.Where(c => c.Join_date >= yesterday && c.Join_date < yesterdayEnd)

你不需要去掉时间,你只需要确保你做的不是完全匹配。

试试这个:

DateTime today = DateTime.Today; // read once, avoid "odd" errors once in a blue moon
DateTime yesterday = today.AddDays(-1);
YesterdaysRegistrations = db.tblForumAuthors.Where(
    c => c.Join_date >= yesterday
      && c.Join_date < today).Count();