stephen776
stephen776

Reputation: 9234

How can I select items with Linq by Date while ignoring Time portion of a DateTime property?

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

Answers (4)

Mir Mohamed Ullah
Mir Mohamed Ullah

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

Sergey Kalinichenko
Sergey Kalinichenko

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

cjk
cjk

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

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

 entries.Where( e => e.Property.Date == new DateTime( 2012, 08, 10 ) )

Upvotes: 2

Related Questions