Comparing dates in linq


I would like to query the db for items with a date greater than or equal to a given date.

The date in the db is a datetime and records time.

If the user enters the search string “1/30/2014”, they expect entries that occurred at any time on that date to be returned. However, anything that has a time after 12 am is not returned.

I know I could simply add a day to the search string, but is there a more appropriate way?

if (form["closedend"] != "")
     DateTime d = DateTime.Parse(form["closedend"]);
     traces = traces.Where(s => s.date_Closed >= d);


You can use the Date property to truncate the time part:

 traces = traces.Where(s => s.date_Closed.Date <= d.Date);

On this way you’d include this day since both DateTimes are midnight.

Update if you use LINQ to Entities DateTime.Date is not supported, you could use this solution: Using DateTime in LINQ to Entities

.Where(s => EntityFunctions.TruncateTime(s.date_Closed) <=  EntityFunctions.TruncateTime(d))

Answered By – Tim Schmelter

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.