C# - Compare Two Dates

Given two dates, we have to compare them using C# program.
Submitted by Nidhi, on August 17, 2020 [Last updated : March 19, 2023]

Here, we are writing a C# program that will compare the given two dates and print the earlier date on the console screen.

C# program to compare two dates

//Program to Compare two dates in C#.

using System;

class DateCompareDemo
{
    static int Main()
    {
        DateTime D1 = new DateTime(2019, 08, 15);
        DateTime D2 = new DateTime(2020, 10, 12);
       
        if (D1 < D2)
            Console.WriteLine(D1);
        else
            Console.WriteLine(D2);
        
        return 0;
    }
}

Output

8/15/2019 12:00:00 AM
Press any key to continue . . .

Explanation

In the above program, we created a class DateCompareDemo that contains the Main() method. In the Main() method we created two objects D1 and D2 of DateTime class that are initialized with date values.

if (D1 < D2)
    Console.WriteLine(D1);
else
    Console.WriteLine(D2);

In the above code, we compared dates using less than "<" operator, in our example D1 is an earlier date then it will be printed on the console screen.

C# Date Time Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.