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
Building on @richardschneider answer, my solution adds a boundary range type as a parameter.
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;
}
}
FWIW, BETWEEN is inclusive, not exclusive WRT to its bounds. Anyway, here you go:
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;
}
This way is fast and the parameters are reversible:
public static bool BetweenInclusive(this DateTime value, DateTime a, DateTime b)
{
return ((a <= value) && (value <= b)) || ((b <= value) && (value <= a));
}