當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# DateTimeOffset.Compare()用法及代碼示例


DateTimeOffset.Compare(DateTimeOffset,DateTimeOffset)方法用於比較兩個DateTimeOffset對象,並顯示第一個對象早於第二個對象,等於第二個對象還是第二個對象。

用法: public static int Compare (DateTimeOffset first, DateTimeOffset second);

參數:
first:這是要比較的第一個對象。
second:這是要比較的第二個對象。


返回值:此方法返回一個帶符號的整數,該整數指示第一個參數的值早於,晚於或與第二個參數的值相同。

  • 小於零:意思是第一要早於第二。
  • 零:意思是第一等於第二。
  • 大於零:意思是第一要晚於第二。

以下示例程序旨在說明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

參考:



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 DateTimeOffset.Compare() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。