Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Problem

I want to compare "dd-mm-yyyy" DateTime's without factoring in the time.

Attempt

I have tried comparing the standard DateTime values with my database DateTime's like this:

C#/LINQ:

 var startDate = DateTime.Today.AddDays(-10);
 var endDate = DateTime.Today;     
     dateList= (from x in db.MY_DB
         where (x.DATE >= startDate && x.DATE < endDate)   
         select x).ToList();

However, my list never gets populated, even though many entries meet this criteria, which I verified with the following query in SQL:

SQL Query:

Select * from db.my_db where date between '13-JUN-2016' and '23-JUN-2016';
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
197 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use DbFunctions.TruncateTime or EntityFunctions.TruncateTime based on your Entity Framework version which:

When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

var start = DateTime.Now.Date.AddDays(-10);
dateList = (from x in db.MY_DB
    where ((DbFunctions.TruncateTime(x.DATE) < DateTime.Now.Date) &&
    ((DbFunctions.TruncateTime(x.DATE) >= start)
    select x).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...