tags:

views:

31

answers:

5

How i do check whether DateTime data type variable is null/empty in asp.net ?

+2  A: 

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
RedFilter
+1  A: 

A DateTime is a value-type, so it can't be null. Is your variable actually typed as DateTime?

LukeH
A: 

It's defaultly initialized to DateTime.MinValue, so you should only check that (unless it's of type DateTime?):

if (MyDateTime==DateTime.MinValue)
...
Oren A
A: 
if !d.HasValue

Hasvalue is a property present in all made-nullable types. (Basically a generic class Nullable)

Joachim VR
A: 

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) ...
Gimly