问题描述
我有两个可以为空的日期时间对象,我想比较两者.最好的方法是什么?
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)
{
}
这篇关于比较可为空的日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!