How to check if DateTime object is null

x4iiiis picture x4iiiis · Oct 21, 2015 · Viewed 13.5k times · Source

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?

Answer

Jakub Lortz picture Jakub Lortz · Oct 21, 2015

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.