问题
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';
回答1:
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();
回答2:
Dates have no format, they are binary values. If the type of the database column is one of the date types, eg date
, datetime
, datetime2
etc, you could search for any record in the past 10 days like this:
var startDate=DateTime.Today.AddDays(-10);
var dateQuery=from row in db.MyTable
where row.Date >=startDate;
To search for a date up to now:
var startDate=DateTime.Today.AddDays(-10);
var endDate=DateTime.Now;
var dateQuery=from row in db.MyTable
where row.Date >=startDate && row.Date<endDate;
If there is any chance that there are entries today that occur later that Now
, you can change the end parameter to tomorrow midnight. The rest of the query remains the same:
var startDate=DateTime.Today.AddDays(-10);
var endDate=DateTime.Today.AddDays(1);
var dateQuery=from row in db.MyTable
where row.Date >=startDate && row.Date<endDate;
回答3:
Using the Microsoft Northwind example db, I wrote the equivalent LINQ:
var endDate = new DateTime(1996, 8, 1);
var startDate = endDate.AddDays(-10);
var dateList= (from x in Orders
where (x.OrderDate >= startDate && x.OrderDate < endDate)
select x).ToList();
dateList.Dump();
and to worked exactly right.
Now, I'm going to assume that you are using Oracle, which I'm pretty sure uses that date display format, which call into question the accuracy of the Linq to PL-SQL transaction. As I recall, that's handled by a third-party provider
来源:https://stackoverflow.com/questions/37991696/compare-dd-mm-yyyy-datetime