我希望使用LINQ to SQL获取今天输入的记录。我写了下面的代码,但它也返回了以前的日期记录。
DateTime todaysDate = DateTime.Now;
DateTime yesterdaysDate = DateTime.Now.AddDays(-1);
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin > yesterdaysDate && a.singin <= todaysDate)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
请告诉我如何使用LINQ to SQL获取今天输入的记录?
答案 0 :(得分:37)
而不是DateTime.Now
使用DateTime.Today
之类的:
DateTime startDateTime = DateTime.Today; //Today at 00:00:00
DateTime endDateTime = DateTime.Today.AddDays(1).AddTicks(-1); //Today at 23:59:59
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin >= startDateTime && a.singin <= endDateTime)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });
或者您可以尝试以下更简单的版本,
var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
where (a.singin.Date == DateTime.Today)
select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });