Compare nullable datetime objects(比较可为空的日期时间对象)
问题描述
我有两个可以为空的日期时间对象,我想比较两者.最好的方法是什么?
I have two nullable datetime objects, I want to compare both. What is the best way to do it?
我已经试过了:
DateTime.Compare(birthDate, hireDate);
这给出了一个错误,也许它需要 System.DateTime 类型的日期,而我有 Nullable 日期时间.
This is giving an error, maybe it is expecting dates of type System.DateTime and I have Nullable datetimes.
我也试过了:
birthDate > hiredate...
但结果并不如预期...有什么建议吗?
But the results are not as expected...any suggestions?
推荐答案
要比较两个 Nullable<T> 对象,请使用 Nullable.Compare<T> 喜欢:
To compare two Nullable<T> objects use Nullable.Compare<T> like:
bool result = Nullable.Compare(birthDate, hireDate) > 0;
<小时>
你也可以这样做:
You can also do:
使用 Nullable DateTime 的 Value 属性.(记得检查两个对象是否都有一些值)
Use the Value property of the Nullable DateTime. (Remember to check if both object Has some values)
if ((birthDate.HasValue && hireDate.HasValue)
&& DateTime.Compare(birthDate.Value, hireDate.Value) > 0)
{
}
如果两个值都相同 DateTime.Compare 将返回您 0
If both values are Same DateTime.Compare will return you 0
类似的东西
DateTime? birthDate = new DateTime(2000, 1, 1);
DateTime? hireDate = new DateTime(2013, 1, 1);
if ((birthDate.HasValue && hireDate.HasValue)
&& DateTime.Compare(birthDate.Value, hireDate.Value) > 0)
{
}
这篇关于比较可为空的日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较可为空的日期时间对象
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
