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)
{
}
这篇关于比较可为空的日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较可为空的日期时间对象
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
