testing
testing

Reputation: 20279

Use LINQ to compare the date part of DateTime

I want to filter some documents between a different date. First I tried comparing the dates directly, but the time (hour, minutes, second) doesn't have to be considered. Therefore only the date part is needed, but the following approach is wrong:

DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue) {
    filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year >= fromDate.Value.Year
    && d.LastModifiedAt.Value.Month >= fromDate.Value.Month
    && d.LastModifiedAt.Value.Day >= fromDate.Value.Day);
}

DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue) {
    filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year <= toDate.Value.Year
    && d.LastModifiedAt.Value.Month <= toDate.Value.Month
    && d.LastModifiedAt.Value.Day <= toDate.Value.Day);
}

Consider the from date 8/15/2014 12:00:00 AM and the to date 9/15/2014 12:00:00 AM. If the document has the date 8/16/2014 10:06:25 AM it won't be in the results. The reason is that I directly compare each component (year, month, day). Because the day is 16 and 16 > 15 the last condition is not met.

How can I solve this? Should I set the time to one minute before midnight? Or should I calculate the difference?

Upvotes: 0

Views: 1707

Answers (2)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

DateTime has a Date property which returns a DateTime for the same day at midnight:

DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue)
    filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date >= fromDate.Value.Date);

DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue)
    filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date <= toDate.Value.Date);

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500505

Just use the DateTime.Date property:

if (fromDate.HasValue) {
    filterResults = filterResults
        .Where(d => d.LastModifiedAt.Date >= fromDate.Value.Date);
}
if (toDate.HasValue) {
    filterResults = filterResults
        .Where(d => d.LastModifiedAt.Date <= toDate.Value.Date);
}

Upvotes: 7

Related Questions