How to test if a DateTime is between 2 days of week (DayOfWeek)
c#, datetime, dayofweek
Solution
This function is going to need two separate branches depending on whether the difference between start and end date is negative or positive/zero.
I could be totally off-base, but I think this works for all cases:
// No state in method, so made it static
public static bool InBetweenDaysInclusive(DateTime date, DayOfWeek start, DayOfWeek end)
{
DayOfWeek curDay = date.DayOfWeek;
if (start <= end)
{
// Test one range: start to end
return (start <= curDay && curDay <= end);
}
else
{
// Test two ranges: start to 6, 0 to end
return (start <= curDay || curDay <= end);
}
}
For reference, your test data returned the following when I ran it and added Console.WriteLine for each result:
True
True
True
False
Edit: My last explanation was too vague. Here's a fixed one.
The trick is that if `end < start`, then you have two valid ranges: `start` to upper bound and lower bound to `end`. This would result in `(start <= curDay && curDay <= upperBound) || curDay <= end && lowerBound <= curDay)`
However, since they are bounds, `curDay` is always `<= upperBound` and `>= lowerBound`, thus we omit that code.
Problem
In C#, given an arbitrary set of DayOfWeek end points (like, DayOfWeek.Friday and DayOfWeek.Sunday) how would one test if an arbitrary date falls between those two days, inclusive? Example: ``` // result == true; Oct 23, 2010 is a Saturday var result = InBetweenDaysInclusive(new DateTime(2010, 10, 23), DayOfWeek.Friday, DayOfWeek.Sunday); // result == true; Oct 22, 2010 is a Friday result = InBetweenDaysInclusive(new DateTime(2010, 10, 22), DayOfWeek.Friday, DayOfWeek.Sunday); // result == true; Oct 24, 2010 is a Sunday result = InBetweenDaysInclusive(new DateTime(2010, 10, 24), DayOfWeek.Friday, DayOfWeek.Sunday); // result == false; Oct 25, 2010 is a Monday result = InBetweenDaysInclusive(new DateTime(2010, 10, 25), DayOfWeek.Friday, DayOfWeek.Sunday); ``` Thanks!