TimeSpan.Compare() Method in C#


The TimeSpan.Compare() method in C# is used to compare two TimeSpan values and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value.

The return value is -1 if span1 is shorter than span2, 0 if span1=span2, whereas 1 if span1 is longer than span2.

Syntax

The syntax is as follows −

public static int Compare (TimeSpan span1, TimeSpan span2);

Above, the parameter span1 is the 1st time interval to compare, whereas span2 is the 2nd interval to compare.

Example

Let us now see an example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = new TimeSpan(-6, 25, 0);
      TimeSpan span2 = new TimeSpan(1, 11, 25, 20);
      TimeSpan span3 = TimeSpan.MinValue;
      TimeSpan res1 = span1.Add(span2);
      TimeSpan res2 = span2.Add(span3);
      Console.WriteLine("Final Timespan (TimeSpan1 + TimeSpan2) = "+res1);
      Console.WriteLine("Final Timespan (TimeSpan2 + TimeSpan3) = "+res2);
      Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
   }
}

Output

This will produce the following output −

Final Timespan (TimeSpan1 + TimeSpan2) = 1.05:50:20
Final Timespan (TimeSpan2 + TimeSpan3) = -10675197.15:22:45.4775808
Result (Comparison of span1 and span2) = -1

Example

Let us now see another example −

 Live Demo

using System;
public class Demo {
   public static void Main(){
      TimeSpan span1 = new TimeSpan(-6, 25, 0);
      TimeSpan span2 = new TimeSpan(1, 10, 0);
      Console.WriteLine("Result (Comparison of span1 and span2) = "+TimeSpan.Compare(span1, span2));
   }
}

Output

This will produce the following output −

Result (Comparison of span1 and span2) = -1

Updated on: 03-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements