当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。