Linq 选择昨天的日期

发布于 2024-11-01 11:16:29 字数 230 浏览 1 评论 0原文

我已经了解到:

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

肯定有记录具有昨天的加入日期,但这始终返回 0!谁能告诉我我这样做是否正确?

I've got as far as this:

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

There definitely records that have the join date of yesterday, but this returns 0 all the time! Can anyone tell me if I'm doing this correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如痴如狂 2024-11-08 11:16:29

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)

AddDays keeps the Hour/Minute/Second components. You either have to use (if c.Join_date is only the date component):

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

Otherwise, you compare for range:

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)
ぇ气 2024-11-08 11:16:29

你不必削减时间,你只需要确保你没有做完全匹配的事情。

试试这个:

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();

You don't have to strip off the time, you just have to make sure you don't do an exact match.

Try this instead:

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文