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?
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.
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.
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.
DateTime itself is a value type. It cannot be null.
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;
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