DateTimeOffset.CompareTo() Method in C#


The DateTimeOffset.CompareTo() method in C# is used to compares the current DateTimeOffset object to a specified DateTimeOffset object and indicates whether the current object is earlier than, the same as, or later than the second DateTimeOffset object.

It returns an integer value,

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

Syntax

Following is the syntax −

public int CompareTo (DateTimeOffset val);

Above, Val is the object to compare.

Example

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

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset1 = new DateTimeOffset(2019, 09, 09, 8, 20, 10, new TimeSpan(-5, 0, 0));
      DateTimeOffset dateTimeOffset2 = new DateTimeOffset(2019, 09, 09, 8, 20, 10, new TimeSpan(-5, 0, 0));
      Console.WriteLine("DateTimeOffset1 = {0}", dateTimeOffset1);
      Console.WriteLine("DateTimeOffset2 = {0}", dateTimeOffset2);
      int res = dateTimeOffset1.CompareTo(dateTimeOffset2);
      // returns equal to 0 since offset1 is equal to offset2
      Console.WriteLine(res);
   }
}

Output

This will produce the following output −

DateTimeOffset1 = 9/9/2019 8:20:10 AM -05:00
DateTimeOffset2 = 9/9/2019 8:20:10 AM -05:00
0

Example

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

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset1 = new DateTimeOffset(2019, 11, 09, 8, 20, 10, new TimeSpan(-5, 0, 0));
      DateTimeOffset dateTimeOffset2 = new DateTimeOffset(2019, 09, 09, 8, 20, 10, new TimeSpan(-5, 0, 0));
      Console.WriteLine("DateTimeOffset1 = {0}", dateTimeOffset1);
      Console.WriteLine("DateTimeOffset2 = {0}", dateTimeOffset2);
      int res = dateTimeOffset1.CompareTo(dateTimeOffset2);
      // returns >0 since DateTimeOffset1 is later than DateTimeOffset2
      Console.WriteLine(res);
   }
}

Output

This will produce the following output −

DateTimeOffset1 = 11/9/2019 8:20:10 AM -05:00
DateTimeOffset2 = 9/9/2019 8:20:10 AM -05:00
1
raja
Published on 07-Nov-2019 05:51:58
Advertisements