Is there BETWEEN DateTime in C# just like SQL does?

前端 未结 9 1152
悲&欢浪女
悲&欢浪女 2021-01-01 09:13

Is there between DateTime in C# ? I know I can do simple check with if (a > date1 && a < date2) but I was trying to find Between meth

相关标签:
9条回答
  • 2021-01-01 09:35

    Why restrict to just dates, use the IComparable interface.

    public static bool InclusiveBetween (this IComparable a, IComparable b, IComparable c)
    {
        return a.CompareTo(b) >= 0 && a.CompareTo(c) <= 0;
    }
    
    public static bool ExclusiveBetween (this IComparable a, IComparable b, IComparable c)
    {
        return a.CompareTo(b) > 0 && a.CompareTo(c) < 0;
    }
    
    public static bool SqlBetween (this IComparable a, IComparable b, IComparable c)
    {
        return a.InclusiveBetween(b, c);
    }
    
    0 讨论(0)
  • 2021-01-01 09:36

    I use something similar to Richard Schneider's (universal between) and Gary Pendlebury's answer (simpler configurable boundary inclusion)

    public static bool Between(this IComparable value, IComparable lowerBoundary, IComparable upperBoundary, 
        bool includeLowerBoundary=true, bool includeUpperBoundary=true)
    {
        var lower = value.CompareTo(lowerBoundary);
        var upper = value.CompareTo(upperBoundary);
        return (lower > 0 || (includeLowerBoundary && lower == 0)) &&
               (upper < 0 || (includeUpperBoundary && upper == 0));
    }
    
    0 讨论(0)
  • 2021-01-01 09:37

    There is not, but if you obey number line formatting per Code Complete, the raw code looks simpler:

    if((lowDate < a) && (a < highDate)) 
    
    0 讨论(0)
  • 2021-01-01 09:37

    You can add an extension method :

    public static Boolean Between(this DateTime input, DateTime minDate, DateTime maxDate)
    {
        // SQL takes limit in !
        return input >= minDate && input <= maxDate;
    }
    
    0 讨论(0)
  • 2021-01-01 09:47

    There is not a Between function but should be easy enough to add one

    public static bool Between(DateTime input, DateTime date1, DateTime date2)
    {
        return (input > date1 && input < date2);
    }
    
    0 讨论(0)
  • 2021-01-01 09:48

    No, there is not.

    0 讨论(0)
提交回复
热议问题