DateTimeOffset.CompareTo(DateTimeOffset)方法用於將當前DateTimeOffset對象與指定的DateTimeOffset對象進行比較,並指示當前對象是早於,相同還是晚於第二個DateTimeOffset對象。
用法: public int CompareTo (DateTimeOffset other);
Here, it takes an object to compare with the current DateTimeOffset object.
返回值:此方法返回一個有符號整數,該整數指示當前DateTimeOffset對象與其他對象之間的關係。
- 小於零:表示當前的DateTimeOffset對象早於其他對象。
- 零:表示當前的DateTimeOffset對象與其他對象相同。
- 大於零:表示當前的DateTimeOffset對象晚於其他對象。
以下示例程序旨在說明DateTimeOffset.CompareTo(DateTimeOffset)方法的用法:
示例1:
// C# program to demonstrate the
// DateTimeOffset.CompareTo(DateTimeOffset)
// Method
using System;
using System.Globalization;
class GFG {
// Main Method
public static void Main()
{
// creating object of DateTimeOffset
DateTimeOffset offset1 = new DateTimeOffset(2007,
6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));
// creating object of DateTimeOffset
DateTimeOffset offset2 = new DateTimeOffset(2006,
6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));
// comparing two offset1 and offset2
// instance using CompareTo() method
int value = offset1.CompareTo(offset2);
if (value > 0)
{
Console.Write("offset1 is later than offset2 ");
}
else if (value < 0)
{
Console.Write("offset1 is earlier than offset2");
}
else
{
Console.Write("offset1 is equal to offset2");
}
}
}
輸出:
offset1 is later than offset2
示例2:
// C# program to demonstrate the
// DateTimeOffset.CompareTo(DateTimeOffset)
// Method
using System;
using System.Globalization;
class GFG {
// Main Method
public static void Main()
{
// creating object of DateTimeOffset
DateTimeOffset offset1 = new DateTimeOffset(2006,
6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));
// creating object of DateTimeOffset
DateTimeOffset offset2 = new DateTimeOffset(2006,
6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));
// comparing two offset1 and offset2
// instance using CompareTo() method
int value = offset1.CompareTo(offset2);
if (value > 0)
{
Console.Write("offset1 is later than offset2 ");
}
else if (value < 0)
{
Console.Write("offset1 is earlier than offset2");
}
else
{
Console.Write("offset1 is equal to offset2");
}
}
}
輸出:
offset1 is equal to offset2
參考:
相關用法
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 DateTimeOffset.CompareTo() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。