.NET/Answer Detail

How to check if a DateTime field is not null or empty?

8 Points
4 Posts

I have table field of type DateTime with allow null in SQL server database. In entity framework , I need to check if the datetime field has null or not.

I try following but not giving correct result:

// do if myDate has null value
// do if myDate has not null value

What is the correct way to check if datetime has null value?

Total Answered: 2
Total Marked As Answer: 0
Posted On: 12-Oct-2017 04:18
Use model.myDate.HasValue. It will return true if date is not null otherwise false. - Brian  12-Oct-2017 22:12
18 Points
9 Posts
Posted On: 12-Oct-2017 22:48

Try following code:

// do if myDate has null value
// do if myDate has not null value
202 Points
86 Posts
Posted On: 29-Oct-2017 23:02

If you declare a DateTime and initialize with DateTime(), then the default value is DateTime.MinValue, and hence you have to check it like this:


DateTime dat = new DateTime();

if (dat == DateTime.MinValue)
   //date is not unassigned

If the DateTime is nullable, well that's a different story:


DateTime? dat = null;

if (!dat.HasValue)
  //date is not unassigned

When replying / answering a question please:

  1. Read the question and other answers carefully.
  2. Understand that English isn't everyone's first language so be sympathetic of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for explanation, ignore it. rudeness is not allowed.
Let's work to help programmers, not make them feel stupid.


Active User (1)

 Log In to Chat