C# DateTime.Compare()方法案例详解
作者:xusong 时间:2023-08-12 23:41:36
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
来源:https://www.nhooo.com/note/qa0bon.html
标签:C#,DateTime.Compare()
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
实例讲解Android中的AutoCompleteTextView自动补全组件
2022-05-10 15:35:10
![](https://img.aspxhome.com/file/2023/1/122121_0s.jpg)
java多线程-同步块实例讲解
2022-06-21 02:10:41
对指定的网页进行截图的效果 C#版
2022-07-04 03:14:18
深入解析Jdk8中Stream流的使用让你脱离for循环
2023-03-01 21:50:43
使用Springboot 打jar包实现分离依赖lib和配置
2023-01-29 18:35:29
![](https://img.aspxhome.com/file/2023/7/76537_0s.png)
Springboot集成Spring Security实现JWT认证的步骤详解
2021-09-18 13:18:08
![](https://img.aspxhome.com/file/2023/4/113204_0s.png)
SpringBoot2整合activiti6环境搭建过程解析
2023-11-09 02:27:03
![](https://img.aspxhome.com/file/2023/9/59379_0s.png)
Java如何构造DSL方法重构
2021-10-10 02:04:09
基于TCP通信丢包原因总结(推荐)
2022-04-27 04:37:28
Spring Boot 实现图片上传并回显功能
2021-10-11 17:45:20
![](https://img.aspxhome.com/file/2023/6/68776_0s.png)
C#使用System.Net.Mail类实现邮件发送
2022-04-26 01:38:21
java中带参数的try(){}语法含义详解
2021-10-27 05:20:16
![](https://img.aspxhome.com/file/2023/1/76211_0s.jpg)
Java应用EasyExcel工具类
2023-07-07 18:45:32
![](https://img.aspxhome.com/file/2023/2/99902_0s.png)
MyBatis逆向工程的创建和使用
2022-07-18 20:07:55
![](https://img.aspxhome.com/file/2023/3/87213_0s.jpg)
解读Spring定义Bean的两种方式:<bean>和@Bean
2023-01-25 23:37:51
详解Android Lint的原理及其使用
2022-12-23 16:05:47
![](https://img.aspxhome.com/file/2023/4/137484_0s.jpg)
java实现死锁的示例代码
2023-10-12 18:12:40
找出链表倒数第n个节点元素的二个方法
2022-07-20 13:35:40
Unity UGUI教程之实现滑页效果
2022-06-30 10:38:30
![](https://img.aspxhome.com/file/2023/0/104300_0s.gif)
Java 面向对象通过new揭开对象实例化
2021-09-30 20:19:05
![](https://img.aspxhome.com/file/2023/6/122196_0s.png)