【问题标题】:Linq select where date is yesterdayLinq选择日期是昨天
【发布时间】:2011-08-05 01:02:32
【问题描述】:

我已经做到了:

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

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

【问题讨论】:

  • 那些Join_date字段是与加入时间一起存储的还是只是日期?
  • @Lasse,他们也有时间,但我不知道如何在 linq 语句中删除它
  • 你能不能用c.Join_date.Date 去掉时间比较一下,还是我漏掉了什么?

标签: c# asp.net linq datetime


【解决方案1】:

AddDays 保留 Hour/Minute/Second 组件。您要么必须使用(如果 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)

【讨论】:

  • 如果有人在午夜前半秒加入怎么办?你不需要减去第二个。
  • 谢谢,但运气不好,数据库中的字段也有时间,我猜它正在停止工作?
  • 不正确。如果数据库仅保存日期组件,则两个对象的小时/分钟/秒将为 0,计算结果为 true。
  • 啊,我也可以在球场上做 .date,很有魅力,谢谢!
  • 我对原帖的问题评论的评论表明它存储了时间。
【解决方案2】:

你不必浪费时间,你只需要确保你没有做完全匹配。

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多