C#中的DateTime.Equals()方法
使用C#中的DateTime.Equals()方法检查两个DateTime对象或实例是否相等。如果两者相等,则返回TRUE,否则返回FALSE。
语法
以下是语法-
public static bool Equals (DateTime date1, DateTime date2);
示例
现在让我们看一个实现DateTime.Equals()方法的示例-
using System; public class Demo { public static void Main() { DateTime d1 = new DateTime(2019, 09, 10, 5, 15, 25); DateTime d2 = d1.AddMonths(25); Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1); Console.WriteLine("\nNew DateTime (After adding months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2); bool res = DateTime.Equals(d1, d2); if (res) Console.WriteLine("\ndate1 = date2. "); else Console.WriteLine("\ndate1 is not equal to date2. "); } }
输出结果
这将产生以下输出-
Initial DateTime = 10 September 2019, 05:15:25 New DateTime (After adding months) = 10 October 2021, 05:15:25 date1 is not equal to date2.
示例
现在让我们来看另一个实现DateTime.Equals()方法的示例-
using System; public class Demo { public static void Main() { DateTime d1 = new DateTime(2019, 11, 11, 7, 15, 30); DateTime d2 = new DateTime(2019, 11, 11, 7, 15, 30); Console.WriteLine("DateTime1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1); Console.WriteLine("\nDateTime2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2); bool res = DateTime.Equals(d1, d2); if (res) Console.WriteLine("\ndate1 = date2 "); else Console.WriteLine("\ndate1 is not equal to date2 "); } }
输出结果
这将产生以下输出-
DateTime1 = 10 September 2019, 05:15:25 DateTime2 = 10 September 2019, 05:15:25 date1 = date2