Open In App

TimeSpan.Compare() Method in C#

Improve
Improve
Like Article
Like
Save
Share
Report

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);
Parameters: 
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:
 

csharp




// 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: 
 

csharp




// 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:
 

csharp




// 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: 
 

 



Last Updated : 25 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads