DotNet/Answer Detail

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

ethanm
ethanm
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:

if(model.myDate==null)
// do if myDate has null value
else
// 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: 2
Posted On: 12-Oct-2017 04:18

Share:   fb twitter linkedin
Use model.myDate.HasValue. It will return true if date is not null otherwise false.
 - Brian  12-Oct-2017 22:12
Answers
beginer
beginer
48 Points
19 Posts
Marked as answer      

Try following code:

if(!model.myDate.HasValue)
// do if myDate has null value
else
// do if myDate has not null value
Posted On: 12-Oct-2017 22:48
Smith
Smith
306 Points
98 Posts
Marked as answer      

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
}
Posted On: 29-Oct-2017 23:02
great ...
 - Priya  05-May-2018 22:26

Blog

Active User (0)

No Active User!
 Log In to Chat