DateTime.CompareTo() Method in C#


The DateTime.CompareTo() method in C# is used to compare the value of this instance to a specified DateTime value.

Syntax

Following is the syntax −

public int CompareTo (DateTime val);

Above, Val is the date to be compared.

It returns an integer value,

  • <0 − If this instance is earlier than Val
  • 0 − If this instance is the same as Val
  • >0 − If this instance is later than Val

Example

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

using System;
public class Demo {
   public static void Main(){
      DateTime date1 = new DateTime(2019, 05, 20, 6, 20, 40);
      DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);
      Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1);
      Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2);
      int res = date1.CompareTo(date2);
      // returns equal to 0 since date1 is equal to date2
      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

Example

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

using System;
public class Demo {
   public static void Main(){
      DateTime date1 = new DateTime(2019, 08, 20, 6, 20, 40);
      DateTime date2 = new DateTime(2019, 05, 20, 6, 20, 40);
      Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date1);
      Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", date2);
      int res = date1.CompareTo(date2);
      // returns >0 since date1 is later than date2
      Console.WriteLine(res);
   }
}

Output

This will produce the following output −

DateTime 1 = 20 August 2019, 06:20:40
DateTime 2 = 20 May 2019, 06:20:40
1
raja
Published on 07-Nov-2019 06:59:14
Advertisements