Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime comparison not including the most recent date

I'm trying to understand why the following function doesn't work.

public IEnumerable<LogFile> GetLogs(string directory, DateTime start, DateTime end)
{
    DirectoryInfo di = new DirectoryInfo(directory);
    return di.GetFiles("*debug.log").Where(f => f.LastWriteTime > start && f.LastWriteTime <= end).Select(f => new LogFile(f.FullName));
}

Why does the second comparison (f.LastWriteTime <= end) omit the specified end date?

The first comparison (f.LastWriteTime > start) does include the specified start date.

For exampled, if I set the start date to 1/4/2013 and the end date to 1/8/2013 the function return files with the following dates:

1/4/2013, 1/5/2013, 1/6/2013, 1/7/2013

It will not include 1/8/2013, despite the use of <= in the code.

like image 562
dbpullman Avatar asked Dec 11 '22 18:12

dbpullman


1 Answers

You're dealing with date & time values, not just date values.

1/6/2013 4:30 is not equal to 1/6/2013 12:00, despite the fact that the dates are the same.

You can use the Date property on each of the DateTime objects to get new DateTime objects where the time is always midnight.

like image 186
Servy Avatar answered Feb 01 '23 11:02

Servy