ADVERTISEMENT
ADVERTISEMENT

C# program to compare two dates

Comparing two dates in C#: Here, we are going to learn how to compare given two dates in C#?
Submitted by Nidhi, on August 17, 2020

Here we will create a C# program to compare two dates and print the earlier date on the console screen.

Program:

//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 »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.