I have two DateTime
objects: StartDate
and EndDate
. I want to make sure StartDate
is before EndDate
. How is this
This is probably too late, but to benefit other people who might stumble upon this, I used an extension method do to this using IComparable
like this:
public static class BetweenExtension
{
public static bool IsBetween(this T value, T min, T max) where T : IComparable
{
return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);
}
}
Using this extension method with IComparable
makes this method more generic and makes it usable with a wide variety of data types and not just dates.
You would use it like this:
DateTime start = new DateTime(2015,1,1);
DateTime end = new DateTime(2015,12,31);
DateTime now = new DateTime(2015,8,20);
if(now.IsBetween(start, end))
{
//Your code here
}