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


C# DateTimeOffset.CompareTo()用法及代码示例


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