Метод TimeSpan.Compare () в C #

Опубликовано: 7 Марта, 2022

Этот метод используется для сравнения двух значений TimeSpan и возвращает целочисленное значение, которое указывает, является ли первое значение короче, равно или длиннее второго значения.

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.

Ниже приведены программы, иллюстрирующие использование метода TimeSpan.Compare (TimeSpan, TimeSpan) :

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

Ссылка:

  • https://docs.microsoft.com/en-us/dotnet/api/system.timespan.compare?view=netframework-4.7.2
C#