📜  C#中的DateTime.CompareTo()方法

📅  最后修改于: 2021-05-29 14:16:38             🧑  作者: Mango

此方法用于将实例的值与指定的DateTime值进行比较,并指示此实例是早于,等于还是晚于指定的DateTime值。此方法的重载列表中有两种方法,如下所示:

  • CompareTo(DateTime)
  • CompareTo(Object)
CompareTo(DateTime)方法

此方法用于将实例的值与指定的DateTime值进行比较,并返回一个整数,该整数指示此实例是早于,等于还是晚于指定的DateTime值。

句法:

public int CompareTo (DateTime value);

在此,参数是要与当前实例进行比较的对象。

返回值:该方法返回一个带符号的数字,指示此实例和value参数的相对值。

  • 小于零:如果此实例早于value。
  • :如果此实例与value相同。
  • 大于零:如果此实例晚于value。

例子:

// C# code to demonstrate
// CompareTo(DateTime) function
using System;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Taking two DateTime Objects
        DateTime d1 = new DateTime(2018, 12,
                              31, 16, 0, 0);
  
        DateTime d2 = new DateTime(2018, 12,
                              31, 20, 0, 0);
  
        // Using the method
        int res = d1.CompareTo(d2);
  
        string r;
  
        if (res > 0)
            r = "is later than";
  
        else if (res == 0)
            r = "is the same time as";
        else
            r = "is earlier than";
  
        Console.WriteLine("{0} {1} {2}", d1, r, d2);
    }
}
输出:
12/31/2018 16:00:00 is earlier than 12/31/2018 20:00:00
CompareTo(Object)方法

此方法用于将实例的值与包含指定的DateTime值的指定对象进行比较,并返回一个整数,该整数指示此实例是早于,等于还是晚于指定的DateTime值。

句法:

public int CompareTo (object value);

在此,参数是要比较的装箱的对象,或者为null。

返回值:该方法返回一个带符号的数字,指示此实例和value参数的相对值。

  • 小于零:如果此实例早于value。
  • :如果此实例与value相同。
  • 大于零:如果此实例晚于value。

异常:如果该不是DateTime,则此方法将提供ArgumentException。

例子:

// C# code to demonstrate
// CompareTo(Object) function
using System;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Taking a DateTime Object
        DateTime d1 = new DateTime(2018, 12,
                              31, 16, 0, 0);
                                
        // Using the method
        // Here, "DateTime.Today" is
        // the property of DateTime struct
        int res = d1.CompareTo(DateTime.Today);
  
        string r;
  
        if (res > 0)
            r = "is later than";
  
        else if (res == 0)
            r = "is the same time as";
        else
            r = "is earlier than";
  
        Console.WriteLine("{0} {1} {2}", d1, r, 
                                DateTime.Today);
    }
}

输出:

12/31/2018 16:00:00 is earlier than 01/21/2019 00:00:00

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.datetime.compareto?view=netframework-4.7.2