I'm looking to validate a DateTime
variable to ensure that it isn't blank on the UI. The string equivalent checking would be String.IsNullOrEmpty()
, but how would I go about it with my DateTime
variable?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.