检查日期是否在范围内的最简洁方法(可以为空)

时间:2017-06-05 23:43:44

标签: c#

检查提供的日期是否在给定日期范围内的最简洁方法是什么? 例如:

DateTime? maxDate
DateTime? minDate
DateTime? userDate

我想检查userDate是否在范围内。其中min或max可以为null。

例如:

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

在这种情况下,userDate将在范围内,因为它比minDate大,并且没有指定maxDate。

我考虑过使用DateTime.Compare,但似乎我会创建一堆if / then语句将userDate检查为minDate和maxDate变量,因为DateTime.Compare一次只能比较2个日期。

3 个答案:

答案 0 :(得分:2)

假设null min / max意味着在这个方向上“无限制”,你可以利用DateTime本身已经限制的事实。

例如:

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;
}

我不确定你想要处理userDate = null的情况。这是否在范围内?所以我的示例函数不允许它。对于这种情况,如果要定义该行为,则可以显式处理它。

答案 1 :(得分:1)

您可以这样做:

  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);
    }

答案 2 :(得分:0)

if((minDate == null || minDate < userDate) && (maxDate == null || maxDate > userDate)) {
    // Do something
}