Linq query between dates

if ((!(searchStartDate == default(DateTime))) && (!(searchEndDate == default(DateTime))))
{
    requests = requests.Where(x => x.CreatedDate >= searchStartDate && x.CreatedDate <= searchEndDate);
}

When I try to search with searchEndDate the date isn't included

Eg.) When the start date is 14/4/15 and end date is 14/4/15 no results are returned but when the start date is 14/4/15 and end date is 15/4/15 results are returned for the 14/4/15

Jon Skeet
people
quotationmark

I strongly suspect the problem is that your start and end date values are the exact same point in time - so only values at that exact point in time will be found.

For example, suppose you have:

searchStartDate: 2015-04-15T00:00:00
searchEndDate: 2015-04-15T00:00:00
Sample CreatedDate: 2015-04-15T12:34:56

Then the CreatedDate doesn't fall between searchStartDate and searchEndDate. You're really thinking of it as:

// Look ma, no time of day!
searchStartDate: 2015-04-15
searchEndDate: 2015-04-15

but because DateTime is a broken model, you can't indicate that with the type system. Instead, you basically need to do it by hand:

if (searchStartDate != default(DateTime) && searchEndDate != default(DateTime))
{
    // Include the *whole* of the day indicated by searchStartDate
    DateTime inclusiveStart = searchStartDate.Date;
    // Include the *whole* of the day indicated by searchEndDate
    DateTime exclusiveEnd = searchEndDate.Date.AddDays(1);
    requests = requests.Where(x => x.CreatedDate >= inclusiveStart
                                && x.CreatedDate < exclusiveEnd);
}

You could put use .Date in the query as well, but that may well be less efficient, as it effectively involves a calculation on each stored value - whereas my approach instead performs a calculation on the bounds instead, just once.

people

See more on this question at Stackoverflow