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("
New 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("
date1 = date2. "); else Console.WriteLine("
date1 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("
DateTime2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2); bool res = DateTime.Equals(d1, d2); if (res) Console.WriteLine("
date1 = date2 "); else Console.WriteLine("
date1 is not equal to date2 "); } }
输出
此代码将生成以下输出 −
DateTime1 = 10 September 2019, 05:15:25 DateTime2 = 10 September 2019, 05:15:25 date1 = date2
广告