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

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

此方法用于比较两个DateTime实例,并返回一个整数,该整数指示第一个实例是早于,等于还是晚于第二个实例。

句法:

public static int Compare (DateTime t1, DateTime t2);

参数:

  • t1:要比较的第一个对象。
  • t2:要比较的第二个对象。

返回值:该方法返回一个带符号的数字,指示t1和t2的相对值。

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

范例1:

// C# program to demonstrate the
// DateTime.Compare(DateTime,
// DateTime) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        // creating object of DateTime
        DateTime date1 = new DateTime(2010, 1, 
                                 1, 4, 0, 15);
  
        // creating object of DateTime
        DateTime date2 = new DateTime(2010, 1,
                                 1, 4, 0, 14);
  
        // comparing date1 and date2
        // using Compare() method;
        int value = DateTime.Compare(date1, date2);
  
        // checking
        if (value > 0)
            Console.Write("date1 is later than date2. ");
        else if (value < 0)
            Console.Write("date1 is earlier than date2. ");
        else
            Console.Write("date1 is the same as date2. ");
    }
}
输出:
date1 is later than date2.

范例2:

// C# program to demonstrate the
// DateTime.Compare(DateTime, 
// DateTime) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // calling check() method
        check(new DateTime(2010, 1, 3, 4, 0, 15),
              new DateTime(2010, 1, 4, 4, 0, 15));
  
        check(new DateTime(2010, 1, 5, 4, 0, 15),
              new DateTime(2010, 1, 4, 4, 0, 15));
  
        check(new DateTime(2010, 1, 5, 4, 0, 15),
              new DateTime(2010, 1, 5, 4, 0, 15));
    }
  
    public static void check(DateTime date1,
                            DateTime date2)
    {
  
        // comparing date1 and date2
        // using Compare() method;
        int value = DateTime.Compare(date1, date2);
  
        // checking
        if (value > 0)
            Console.WriteLine(" {0:d} is later than {1:d}. ",
                                               date1, date2);
        else if (value < 0)
            Console.WriteLine(" {0:d} is earlier than {1:d}. ",
                                                 date1, date2);
        else
            Console.WriteLine(" {0:d} is the same as {1:d}. ",
                                                date1, date2);
    }
}
输出:
01/03/2010 is earlier than 01/04/2010. 
01/05/2010 is later than 01/04/2010. 
01/05/2010 is the same as 01/05/2010.

参考:

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