Reputation: 341
How i do check whether DateTime data type variable is null/empty in asp.net ?
Upvotes: 1
Views: 507
Reputation: 171579
For a nullable DateTime
type, you can just compare against null like this:
DateTime? d = null;
if (d == null)
//do something
For a non-nullable DateTime
type you can compare against the default MinValue
:
DateTime d2;
if (d2 == DateTime.MinValue)
//do something else
Upvotes: 2
Reputation: 6175
DateTime is a value type, therefore it cannot be null/empty. (see this msdn entry for reference).
By default it will get the value of DateTime.MinValue, so you could check if it is equal to that, but it's not the best solution.
The best solution would be to create a Nullable variable of this type. The syntax is the following:
Nullable<DateTime> myNullableDate = ...
if(myNullableDate.HasValue) ...
You can also use the question mark, this way, which is a bit simpler to read:
DateTime? myNullableDate = ...
if(myNullableDate.HasValue) ...
Upvotes: 0
Reputation: 2340
if !d.HasValue
Hasvalue is a property present in all made-nullable types. (Basically a generic class Nullable)
Upvotes: 0
Reputation: 5900
It's defaultly initialized to DateTime.MinValue, so you should only check that (unless it's of type DateTime?
):
if (MyDateTime==DateTime.MinValue)
...
Upvotes: 0
Reputation: 269658
A DateTime
is a value-type, so it can't be null. Is your variable actually typed as DateTime
?
Upvotes: 1