我已经达到了这个目标:
DateTime yesterday = DateTime.Today.AddDays(-1);
YesterdaysRegistrations = db.tblForumAuthors.Where(c => c.Join_date == yesterday).Count();
肯定会有昨天的加入日期的记录,但这会一直返回0!任何人都可以告诉我,如果我这样做是正确的吗?
答案 0 :(得分:9)
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)
答案 1 :(得分:4)
你不必剥离时间,你只需要确保你没有完全匹配。
请改为尝试:
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();