Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare nullable datetime objects

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?

like image 631
faizanjehangir Avatar asked Jan 10 '13 06:01

faizanjehangir


People also ask

Can we compare date with null?

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.

How to handle null value for DateTime in c#?

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.

How to check if DateTime is null c#?

Use model. myDate. HasValue. It will return true if date is not null otherwise false.


1 Answers

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)
{
}
like image 119
Habib Avatar answered Oct 14 '22 08:10

Habib