C#中的BETWEEN DateTime就像SQL一样吗?

C#中的DateTime之间有没有? 我知道我可以用if (a > date1 && a < date2)进行简单检查,但我试图找到Between方法。

没有Betweenfunction,但应该很容易添加一个

 public static bool Between(DateTime input, DateTime date1, DateTime date2) { return (input > date1 && input < date2); } 

为什么限制只是日期,使用IComparable接口 。

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

不,那里没有。

FWIW,BETWEEN是包容性的,而非WRT到它的范围。 无论如何,你走了:

 public static bool Between(this DateTime instant, DateTime dtFrom , DateTime dtThru ) { if (dtFrom > dtThru) throw new ArgumentException( "dtFrom may not be after dtThru", "dtFrom" ); bool isBetween = ( instant >= dtFrom && instant <= dtThru ); return isBetween; } 

在@richardschneider答案的基础上,我的解决方案添加了边界范围类型作为参数。

 public enum RangeBoundaryType { [Description("Exclusive")] Exclusive, [Description("Inclusive on both boundaries")] Inclusive, [Description("Inclusive on only the lower boundary")] InclusiveLowerBoundaryOnly, [Description("Inclusive on only the upper boundary")] InclusiveUpperBoundaryOnly } public static bool Between(this IComparable value, IComparable comparator0, IComparable comparator1, RangeBoundaryType rangeBoundary) { switch (rangeBoundary) { case RangeBoundaryType.Exclusive: return (value.CompareTo(comparator0) > 0 && value.CompareTo(comparator1) < 0); case RangeBoundaryType.Inclusive: return (value.CompareTo(comparator0) >= 0 && value.CompareTo(comparator1) <= 0); case RangeBoundaryType.InclusiveLowerBoundaryOnly: return (value.CompareTo(comparator0) >= 0 && value.CompareTo(comparator1) < 0); case RangeBoundaryType.InclusiveUpperBoundaryOnly: return (value.CompareTo(comparator0) > 0 && value.CompareTo(comparator1) <= 0); default: return false; } } 

没有,但如果您遵守每个代码完成的数字行格式,原始代码看起来更简单:

 if((lowDate < a) && (a < highDate)) 

您可以添加扩展方法:

 public static Boolean Between(this DateTime input, DateTime minDate, DateTime maxDate) { // SQL takes limit in ! return input >= minDate && input <= maxDate; } 

我使用类似于Richard Schneider (通用之间)和Gary Pendlebury的答案 (更简单的可配置边界包含)

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

这种方式很快,参数是可逆的:

 public static bool BetweenInclusive(this DateTime value, DateTime a, DateTime b) { return ((a <= value) && (value <= b)) || ((b <= value) && (value <= a)); }