Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 485
tintyethan Avatar asked Oct 08 '14 14:10

tintyethan


1 Answers

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))
like image 147
Tim Schmelter Avatar answered Sep 26 '22 13:09

Tim Schmelter