DateTimeOffset.CompareTo(DateTimeOffset)方法用于将当前DateTimeOffset对象与指定的DateTimeOffset对象进行比较,并指示当前对象是早于,相同还是晚于第二个DateTimeOffset对象。
Syntax: public int CompareTo (DateTimeOffset other);
Here, it takes an object to compare with the current DateTimeOffset object.
Return Value: This method returns a signed integer that indicates the relationship between the current DateTimeOffset object and other.
- Less than zero: Means the current DateTimeOffset object is earlier than other.
- Zero: Means the current DateTimeOffset object is the same as other.
- Greater than zero: Means the current DateTimeOffset object is later than other.
下面的程序说明了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
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.datetimeoffset.compareto?view=netframework-4.7.2