1

What is the cleanest way to check if a supplied date is in a given date range? For example:

DateTime? maxDate
DateTime? minDate
DateTime? userDate

I want to check if the userDate is in the range. Where min or max can be null.

So for example:

minDate = new DateTime(2017, 1, 1);
maxDate = null;
userDate = new DateTime(2017, 5, 3);

In this scenario userDate would be in the range since it's greater then the minDate and no maxDate was specified.

I thought about using DateTime.Compare but it seems that I would create a mess of if/then statements to check userDate to the minDate and maxDate variables since the DateTime.Compare will only compare 2 dates at a time.

John Doe
  • 3,053
  • 17
  • 48
  • 75

3 Answers3

2

Assuming null min/max would mean 'unbounded' in that direction, you could take advantage of the fact that DateTime itself has bounds.

For example:

public bool IsDateInRange(DateTime value, DateTime? min, DateTime? max)
{
    //Use provided min/max times if they were not null. Fallback to Min/Max supported values from DateTime
    min = min ?? DateTime.MinValue;
    max = max ?? DateTime.MaxValue;

    return value >= min && value <= max;
}

I'm not really sure how you would want to handle the case where userDate = null. Is that ever in range? So my example function doesn't allow it. For that case, you could handle it explicitly if you want to define that behavior.

Khalos
  • 2,335
  • 1
  • 23
  • 38
  • 1
    Good answer. On a side note, you should [convert to UTC when comparing dates](https://stackoverflow.com/questions/6930489/safely-comparing-local-and-universal-datetimes) or else you may end up with an incorrect comparison, especially if you are comparing times that fall within the extra hour added or removed for DST, – John Wu Jun 05 '17 at 23:58
  • To add to this, you could use minDate.GetValueOrDefault(DateTime.MinValue) – Tony Basallo Jun 06 '17 at 03:26
1

You can do like this:

  public static bool IsInRange(this DateTime dateToCheck, DateTime? startDate, DateTime? endDate)
    {
        return (startDate.HasValue && dateToCheck.Date >= startDate.Value.Date) &&
               (endDate.HasValue && dateToCheck.Date <= endDate.Value.Date);
    }
hummer007
  • 11
  • 1
0
if((minDate == null || minDate < userDate) && (maxDate == null || maxDate > userDate)) {
    // Do something
}
Frederik Hansen
  • 506
  • 4
  • 21