Compare nullable datetime objects
Nullable.Equals Indicates whether two specified Nullable(Of T) objects are equal.
Try:
if(birthDate.Equals(hireDate))
The best way would be: Nullable.Compare Method
Nullable.Compare(birthDate, hireDate));
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 want a null
value to be treated as default(DateTime)
you could do something like this:
public class NullableDateTimeComparer : IComparer<DateTime?>
{
public int Compare(DateTime? x, DateTime? y)
{
return x.GetValueOrDefault().CompareTo(y.GetValueOrDefault());
}
}
and use it like this
var myComparer = new NullableDateTimeComparer();
myComparer.Compare(left, right);
Another way to do this would be to make an extension method for Nullable
types whose values are comparable
public static class NullableComparableExtensions
{
public static int CompareTo<T>(this T? left, T? right)
where T : struct, IComparable<T>
{
return left.GetValueOrDefault().CompareTo(right.GetValueOrDefault());
}
}
Where you'd use it like this
DateTime? left = null, right = DateTime.Now;
left.CompareTo(right);