Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

c# - Compare dd-mm-yyyy datetime

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...