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<T>(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
}
StartDate < EndDate
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
if(StartDate < EndDate)
{}
DateTime supports normal comparision operators.
You can use the overloaded < or > operators.
For example:
DateTime d1 = new DateTime(2008, 1, 1);
DateTime d2 = new DateTime(2008, 1, 2);
if (d1 < d2) { ...
Check out DateTime.Compare method