How to check if one DateTime is greater than the other in C#

Viewed 203532

I have two DateTime objects: StartDate and EndDate. I want to make sure StartDate is before EndDate. How is this done in C#?

10 Answers
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) { ...
if (StartDate>=EndDate)
{
    throw new InvalidOperationException("Ack!  StartDate is not before EndDate!");
}

Check out DateTime.Compare method

        if (new DateTime(5000) > new DateTime(1000))
        {
            Console.WriteLine("i win");
        }
Related