I'm cognitively struggling with a probably fairly simple problem. Given a certain DateTime, how can I verify that this date (without accounting its year) is in between two other dates?
An example:
DateTime toCheck = new DateTime(1900, 3, 4);
DateTime min = new DateTime(2024, 1, 1);
DateTime max = new DateTime(2024, 12, 31);
// True - 'toCheck' is between 'min' and 'max'
In the snippet above, toCheck is in between min and max because 3rd April is between 1st January and 31st December. I can easily verify this with something like new DateTime(min.Year, toCheck.Month, toCheck.Day) >= min && new DateTime(max.Year, toCheck.Month, toCheck.Day) <= max;.
However, I realized this gets more complicated when years overlap. For instance, in the following scenario, January 1st is between December 1st and February 1st but my check fails (obviously).
DateTime toCheck = new DateTime(1900, 1, 1);
DateTime min = new DateTime(2024, 12, 1);
DateTime max = new DateTime(2025, 2, 1);
// False - but should actually be True :(
I just can't wrap my head around writing a general, bulletproof solution. Any help is highly appreciated.
Link to dotnetfiddle.net
The logic is simple:
This also works when the [min, max] range crosses the year boundary, like from December to February. In a very specific case where the end date needs to be the end of February, use 0229 as the end date.
Converting the above logic to the language of your choice is trivial.
dotnet fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With