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)
{
}
这篇关于比较可为空的日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较可为空的日期时间对象


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01