比较可空datetime对象 [英] Compare nullable datetime objects
问题描述
我有两个可空datetime对象,我想比较两者。 ?什么是做到这一点的最好办法
I have two nullable datetime objects, I want to compare both. What is the best way to do it?
我已经尝试:
DateTime.Compare(birthDate, hireDate);
这是给了一个错误,键入系统也许期待日期。 。日期时间
和我有可空日期时间
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?
推荐答案
要比较两个可空< 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:
使用可空的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)
{
}
这篇关于比较可空datetime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!