此方法用於比較兩個TimeSpan值,並返回一個整數值,該整數值指示第一個值是小於,等於還是大於第二個值。
用法: public static int Compare (TimeSpan t1, TimeSpan t2);
參數:
11:指定要比較的第一個時間間隔。
t2:指定要比較的第二個時間間隔。
返回值:
-1:如果t1短於t2。
0:如果t1等於t2。
1個:如果t1大於t2。
以下示例程序旨在說明TimeSpan.Compare(TimeSpan,TimeSpan)方法的用法:
示例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");
}
}
輸出:
t1 is greater than t2
示例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");
}
}
輸出:
t2 is greater than t1
示例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");
}
}
輸出:
t1 is equal to t2
參考:
相關用法
- C# Dictionary.Add()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Queue.Contains()用法及代碼示例
- C# Stack.Pop()用法及代碼示例
注:本文由純淨天空篩選整理自IshwarGupta大神的英文原創作品 TimeSpan.Compare() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。