Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Nullable DateTime variable for default value

In my C# code, I have a DateTime? variable. While getting the values from database it can be null or can have some date/time value.

On the front end side I don't want to get the default value (01-01-1900 12:00:00 am). Whats the best way to compare my date variable for this default date?

like image 225
V.B Avatar asked Oct 17 '12 06:10

V.B


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 do you handle null in DateTime?

Using the DateTime nullable type, you can assign the null literal to the DateTime type. A nullable DateTime is specified using the following question mark syntax. DateTime? The following is the code to implement Nullable Datetime.

What is the value of default DateTime?

The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight). The maximum value can be December 31, 9999 11:59:59 P.M. Use different constructors of the DateTime struct to assign an initial value to a DateTime object.

Should DateTime be nullable?

DateTime itself is a value type. It cannot be null.


1 Answers

You can create a const:

static readonly DateTime DefaultDateTime = new DateTime(1900, 1, 1, 0, 0, 0);

and then compare this way:

DateTime? myVariable = returnedFromDb == DefaultDateTime ? default(DateTime?) : returnedFromDb;
like image 162
Adam Kostecki Avatar answered Nov 13 '22 07:11

Adam Kostecki