DateTime comparison, not including the most recent date

I am trying to understand why the following function does not 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 (f.LastWriteTime <= end) second comparison (f.LastWriteTime <= end) omit the specified end date?

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

For the sample, if I set the start date to 1/4/2013 and the end date to 1/8/2013, the function returns 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 using <= in the code.

+4
source share
3 answers

You are dealing with date and time values, not just date values.

1/6/2013 4:30 not equal 1/6/2013 12:00 , even though the dates are the same.

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

+9
source

DateTime also contains (as the name implies) a time component. So your comparison is actually:

 f.LastWriteTime > start && f.LastWriteTime <= end f.LastWriteTime > 1/4/2013 00:00:00 && f.LastWriteTime <= 1/8/2013 00:00:00 

The last date of the file is probably something like 1/8/2013 13:45:12, so

 1/8/2013 13:45:12 <= 1/8/2013 00:00:00 

is false. Due to the time component, the first data relevance is included in the result:

 1/4/2013 00:00:00 > 1/4/2013 13:45:12 

truly.

+4
source

But when compared with the date of the date, the last second of the value is not included: time <= 1/14/2013 1:26:42, does this include 1/14/2013 1:26:41 AM?

0
source

All Articles