DateTime.Compare() Method in C#


The DateTime.Compare() method in C# is used for comparison of two DateTime instances. It returns an integer value,

  • <0 − If date1 is earlier than date2
  • 0 − If date1 is the same as date2
  • >0 − If date1 is later than date2

Syntax

Following is the syntax −

public static int Compare (DateTime d1, DateTime d2);

Above, d1 and d2 are the two dates to be compared.

Example

Let us now see an example to implement the DateTime.Compare() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 20, 6, 20, 40);
      DateTime d2 = d1.AddYears(5);
      Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      Console.WriteLine("New DateTime (adding years) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
      int res = DateTime.Compare(d1, d2);
      // returns <0 since d1 is earlier than d2
      Console.WriteLine(res);
   }
}

Output

This will produce the following output −

Initial DateTime = 20 November 2019, 06:20:40
New DateTime (adding years) = 20 November 2024, 06:20:40
-1

Example

Let us now see another example to implement the DateTime.Compare() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 20, 6, 20, 40);
      DateTime d2 = new DateTime(2019, 11, 20, 6, 20, 40);
      Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
      int res = DateTime.Compare(d1, d2);
      // returns equal to 0 since d1 is equal to d2
      Console.WriteLine(res);
   }
}

Output

This will produce the following output −

DateTime 1 = 20 November 2019, 06:20:40
DateTime 2 = 20 November 2019, 06:20:40
0

Updated on: 02-Sep-2023

43K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements