I couldn’t find best solution when DateTime value is NULL.
I use this techinque When binding;
_ACTIVATION_DATE = dt.Rows[0]["ACTIVATION_DATE"] == DBNull.Value ? new DateTime(1970, 12, 30) : (DateTime?)dt.Rows[0]["ACTIVATION_DATE"];
When Inserting;
public void Insert()
{
string ad="";
string dd="";
if (ACTIVATION_DATE == null)
ad = "null";
else
ad = "'" + ACTIVATION_DATE + "'";
if (DEACTIVATION_DATE == null)
dd = "null";
else
dd = "'" +DEACTIVATION_DATE +"'";
string sSQL = "INSERT INTO LINE_INFO (ACTIVATION_DATE,DEACTIVATION_DATE,STATUS,PO,NOTES) VALUES (" + ad + "," + dd + "," + _STATUS.ToString() + "," + _PO.ToString() + ",'" + _NOTES.ToString() + "');SELECT @@IDENTITY AS LASTID";
}
Variables;
DateTime? ACTIVATION_DATE;
DateTime? DEACTIVATION_DATE;
What is the smart way to handle Null DateTime values?
When I find the solution I will write an article about this topic.
Why are you using
new DateTime(1970, 12, 30)when you’re already using a nullable DateTime? The whole point of nullable value types is that you don’t need magic values like that.I would possibly use:
That will automatically use the null value for any non-DateTime value. Of course, that means you’ll get a null value instead of an exception if you accidentally have an integer or something like that. Alternatively:
Then for the insert statement, do not include values directly in your SQL. Use a parameterized insert statement, and then you can just use a null
DateTime?value to insert a null value. No need to mess around with string formats.