Skip to content
Related Articles

Related Articles

TimeSpan.Compare() Method in C#
  • Last Updated : 13 Feb, 2019

This method is used to compare two TimeSpan values and returns an integer value which indicates whether the first value is shorter than, equal to, or longer than the second value.

Syntax: public static int Compare (TimeSpan t1, TimeSpan t2);

Paramaters:
t1: Specifies the first time interval that will be compared.
t2: Specifies the second time interval that will be compared.

Return Value:
-1: If t1 is shorter than t2.
0: If t1 is equal to t2.
1: If t1 is longer than t2.

Below programs illustrate the use of TimeSpan.Compare(TimeSpan, TimeSpan) Method:



Example 1:




// C# program to demonstrate the
// TimeSpan.Compare(TimeSpan, 
// TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating the TimeSpans
        TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
        TimeSpan t2 = new TimeSpan(1, 11, 15, 16);
  
        if (TimeSpan.Compare(t1, t2) == 1)
            Console.Write("t1 is greater than t2");
  
        else if (TimeSpan.Compare(t1, t2) == 0)
            Console.Write("t1 is equal to t2");
  
        else
            Console.Write("t2 is greater than t1");
    }
}


Output:

t1 is greater than t2

Example 2:




// C# program to demonstrate the
// TimeSpan.Compare(TimeSpan, 
// TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating the TimeSpans
        TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
        TimeSpan t2 = new TimeSpan(4, 31, 15, 10);
  
        if (TimeSpan.Compare(t1, t2) == 1)
            Console.Write("t1 is greater than t2");
  
        else if (TimeSpan.Compare(t1, t2) == 0)
            Console.Write("t1 is equal to t2");
  
        else
            Console.Write("t2 is greater than t1");
    }
}


Output:

t2 is greater than t1

Example 3:




// C# program to demonstrate the
// TimeSpan.Compare(TimeSpan, 
// TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // creating the TimeSpans
        TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
        TimeSpan t2 = new TimeSpan(3, 22, 35, 33);
  
        if (TimeSpan.Compare(t1, t2) == 1)
            Console.Write("t1 is greater than t2");
  
        else if (TimeSpan.Compare(t1, t2) == 0)
            Console.Write("t1 is equal to t2");
  
        else
            Console.Write("t2 is greater than t1");
    }
}


Output:

t1 is equal to t2

Reference:

My Personal Notes arrow_drop_up
Recommended Articles
Page :