How to check if DateTime object is null
Solution 1
DateTime
is a value type, so it cannot be null. To check if a DateTime
variable has the default (all 0) value you can compare it with new DateTime()
or default(DateTime)
.
Another option would be to use DateTime?
instead of DateTime
for user input and check HasValue
property.
Solution 2
To check if a DateTime
is null in C#, you must first ensure the DateTime is nullable.
// DateTime? means it is nullable
var DateTime? date = null;
// .HasValue only exists if DateTime is nullable
if(date.HasValue)
Console.WriteLine("date has a value");
else
Console.WriteLine("date is null");
If your DateTime
is not nullable, make it nullable (unless you are absolutely certain in will never be null). You don't want to go down the road of assigning "nullish" values to your DateTimes. In my experience, this creates confusing bugs / code.
x4iiiis
Updated on June 04, 2022Comments
-
x4iiiis about 2 years
I'm looking to validate a
DateTime
variable to ensure that it isn't blank on the UI. The string equivalent checking would beString.IsNullOrEmpty()
, but how would I go about it with myDateTime
variable?