onefootswill onefootswill - 1 month ago 6
C# Question

Unexpected DateTime Range Scenario

I hate dates. So I'm maintaining a project and came across an extension method which is a bit naive, but should do the trick in 99% of cases. It is checking a date range:

public static bool IsInRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
if (startDate <= endDate)
return dateToCheck >= startDate && dateToCheck <= endDate;

return false;

So I have a situation which is baffling me. The return statement in the if scope is returning true when the dateToCheck is after the endDate. See the following screen grab for debugging values:

enter image description here

I considered the fact that they may have a different DateTimeKind, so I added the following statement to ensure they were both local:

DateTime.SpecifyKind(dateToCheck, DateTimeKind.Local)

I am unable to reproduce this in a console application.

So I guess my question is, what the heck!?

Answer Source

If you check your dateToCheck variable closely, the year is 1917 which is obviously smaller than 2017(enddate year is 2017). So, it's working as expected as far as I can see.