Home Programs Compare Two Dates in C#

Compare Two Dates in C#

In this example we compare 2 dates in C#

Example

We store a date in a variable and for the purpose of this example we add 30 days

We then use a simple if statement to check if the startDate is less than the endDate. Ideally you can also check for other conditions

using System;

namespace ConsoleApp1
{
    class Program
    {
        static int Main()
        {
            DateTime startDate = new DateTime(2022, 03, 03);
            Console.WriteLine("Starting Date : {0}", startDate);
            DateTime endDate = startDate.AddDays(30);
            Console.WriteLine("Ending Date   : {0}", endDate);
            if (startDate < endDate)
                Console.WriteLine("{0} Occurs Before {1}", startDate, endDate);
            Console.Read();
            return 0;

        }
    }
}

 

Lets see a test run

Starting Date : 03/03/2022 00:00:00
Ending Date   : 13/03/2022 00:00:00
03/03/2022 00:00:00 Occurs Before 13/03/2022 00:00:00

You may also like