📜  C#中的DateTimeOffset.Compare()方法

📅  最后修改于: 2021-05-29 13:43:30             🧑  作者: Mango

DateTimeOffset.Compare(DateTimeOffset,DateTimeOffset)方法用于比较两个DateTimeOffset对象,并显示第一个是早于第二个,等于第二个还是晚于第二个。

下面的程序说明了DateTimeOffset.Compare(DateTimeOffset,DateTimeOffset)方法的使用:

范例1:

// C# program to demonstrate the
// DateTimeOffset.Compare(DateTimeOffset, 
// 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 Compare() method
        int value = DateTimeOffset.Compare(offset1, 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:对于ArgumentOutOfRangeException

// C# program to demonstrate the
// DateTimeOffset.Compare(DateTimeOffset,
// 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 Compare() method
        int value = DateTimeOffset.Compare(offset1, 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.compare?view=netframework-4.7.2