C# program to compare two dates

C# program to compare two dates:

This program will show you how to compare two dates in C#. We will read the year, month and day as input from the user for both dates and compare them both.

C# program:

Below is the complete C# program:

using System;

public class Program
{
	public static void Main()
	{
		int year1, month1, date1, year2, month2, date2;
        
        Console.WriteLine("Enter data for the first date : ");
		Console.Write("Year : ");
		year1 = Convert.ToInt32(Console.ReadLine());
		
		Console.Write("Month : ");
		month1 = Convert.ToInt32(Console.ReadLine());
		
		Console.Write("Date : ");
		date1 = Convert.ToInt32(Console.ReadLine());
		
		Console.WriteLine("Enter data for the second date : ");
		Console.Write("Year : ");
		year2 = Convert.ToInt32(Console.ReadLine());
		
		Console.Write("Month : ");
		month2 = Convert.ToInt32(Console.ReadLine());
		
		Console.Write("Date : ");
		date2 = Convert.ToInt32(Console.ReadLine());
		
		DateTime dateTime1 = new DateTime(year1, month1, date1);
		DateTime dateTime2 = new DateTime(year2, month2, date2);
		
		if(dateTime1 < dateTime2){
			Console.WriteLine("Time {0} is before {1}", dateTime1, dateTime2);
		}else{
			Console.WriteLine("Time {0} is after {1}", dateTime1, dateTime2);
		}
	}
}

Here,

  • year1, month1, date1, year2, month2, date2 are integer variables to hold the year, month and date data for both dates.
  • It takes the inputs from the user and stored in the variables.
  • Using the user input values, it created two DateTime variables dateTime1 and dateTime2.
  • The last if-else block compares both dateTime1 and dateTime2 and prints one message which one comes before.

Sample output:

It will give output as like below:

Enter data for the first date : 
Year : 2020
Month : 11
Date : 11
Enter data for the second date : 
Year : 2020
Month : 12
Date : 12
Time 11/11/2020 12:00:00 AM is before 12/12/2020 12:00:00 AM

You might also like: