I have two nullable datetime objects, I want to compare both. What is the best way to do it?
I have already tried:
DateTime.Compare(birthDate, hireDate);
This is giving an error, maybe it is expecting dates of type System.DateTime
and I have Nullable datetimes.
I have also tried:
birthDate > hiredate...
But the results are not as expected...any suggestions?
Yes, If declare DateTime variable as nullable like DateTime? then we can compare it with null. And also to be noted if we compare with null it gives us false result because DateTime cannot understand what is null value and to which component of DateTime type it is actually being compared. So it is of no usage.
C# Nullable Type By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.
Use model. myDate. HasValue. It will return true if date is not null otherwise false.
To compare two Nullable<T>
objects use Nullable.Compare<T>
like:
bool result = Nullable.Compare(birthDate, hireDate) > 0;
You can also do:
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)
{
}
If both values are Same DateTime.Compare will return you 0
Something Like
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With