C# DateTime.Compare()方法案例详解
时间:2021-12-03 09:26:11|栏目:.NET代码|点击: 次
C#中的DateTime.Compare()方法用于比较两个DateTime实例。它返回一个整数值,
- <0-如果date1早于date2
- 0-如果date1与date2相同
- > 0-如果date1晚于date2
语法
以下是语法-
public static int Compare (DateTime d1, DateTime d2);
上面的d1和d2是要比较的两个日期。
示例
现在让我们看一个实现DateTime.Compare()方法的示例-
using System; public class Demo { public static void Main(){ DateTime d1 = new DateTime(2019, 11, 20, 6, 20, 40); DateTime d2 = d1.AddYears(5); Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1); Console.WriteLine("New DateTime (adding years) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2); int res = DateTime.Compare(d1, d2); // returns <0 since d1 is earlier than d2 Console.WriteLine(res); } }
输出结果
这将产生以下输出-
Initial DateTime = 20 November 2019, 06:20:40
New DateTime (adding years) = 20 November 2024, 06:20:40
-1
示例
现在让我们来看另一个实现DateTime.Compare()方法的示例-
using System; public class Demo { public static void Main(){ DateTime d1 = new DateTime(2019, 11, 20, 6, 20, 40); DateTime d2 = new DateTime(2019, 11, 20, 6, 20, 40); Console.WriteLine("DateTime 1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1); Console.WriteLine("DateTime 2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2); int res = DateTime.Compare(d1, d2); //由于d1等于d2,所以返回等于0- Console.WriteLine(res); } }
输出结果
这将产生以下输出-
DateTime 1 = 20 November 2019, 06:20:40
DateTime 2 = 20 November 2019, 06:20:40
0
上一篇:Asp.Net各种超时问题总结
栏 目:.NET代码
本文标题:C# DateTime.Compare()方法案例详解
本文地址:http://www.codeinn.net/misctech/185563.html