Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a DateTime lies between a certain date range without taking the year into account?

Tags:

c#

.net

datetime

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

like image 490
Behemoth Avatar asked Oct 30 '25 02:10

Behemoth


1 Answers

The logic is simple:

  • format all three dates in MMdd format for straight forward comparison
  • compare the three values as follows:
  • if min <= max then:
    • is_between = (to_check >= min && to_check <= max)
  • else
    • is_between = (to_check >= min || to_check <= max)

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

like image 112
Salman A Avatar answered Oct 31 '25 16:10

Salman A