Reputation: 9234
I have a list of objects with a DateTime parameter.
I would like to use LINQ to query this list and return entries by date but ignoring the Time portion
So I would like to select any entry that occurs at any time on 08-10-2012.
Upvotes: 8
Views: 2947
Reputation: 45
what about using EntityFunctions.TruncateTime ( EF 6 onwards)
var result = context.Employees
.Where(x => EntityFunctions.TruncateTime(x.LoginDate) ==DateTime.Today)
.FirstOrDefault();
Namespace: System.Data.Objects.EntityFunctions.TruncateTime
Upvotes: 1
Reputation: 727047
You can use this snippet for in-memory queries:
var theDate = new DateTime(2012, 08, 10);
var entriesOnTheDate = list.Where(item => item.DateTimeField.Date.Equals(theDate));
For querying against SQL Server data source, you can use SqlFunctions.DatePart
to extract the day, the month, and the year, and compare them separately.
var entriesOnTheDate = dbContext
.EntriesWithDateTimeField
.Where(item => SqlFunctions.DatePart("Year", item.DateTimeField) == 2012
&& SqlFunctions.DatePart("Month", item.DateTimeField) == 8
&& SqlFunctions.DatePart("Day", item.DateTimeField) == 12);
Upvotes: 8
Reputation: 46475
You can add a range of times that covers your entire day:
entries.Where(e => e.Property.Date >= new DateTime(2012, 08, 10)
&& e.Property.Date < new DateTime(2012, 08, 11));
Upvotes: 2
Reputation: 48314
entries.Where( e => e.Property.Date == new DateTime( 2012, 08, 10 ) )
Upvotes: 2