My SQL Server database contains nullable DateTime values. How can I convert them to a nullable DateTime object in my application in C#?
This is what I would think it would look like, but it doesn’t:
DateTime? dt = (DateTime?) sqldatareader[0];
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A SQL null is not the same as a .NET null; you have to compare against System.DBNull.Value:
In answer to your comment, the data type of the
Itemproperty of aDataReaderis that of the underlying database type. It could beSystem.Data.SqlTypes.SqlDateTimefor a non-null SQL Server database, orSystem.DBNullfor a null column, orSystem.Data.Odbc.OdbcTypes.SmallDateTimefor an ODBC database, or really just about anything. The only thing you can rely on is that it is of typeobject.This is also why I suggest using
Convert.ToDateTime()instead of type coercion toDateTime. There is no guarantee a ODBC or whatever date column can be coerced to a .NETDateTime. I note your comment specifies a “sqldatareader”, and a SQL ServerSystem.Data.SqlTypes.SqlDateTimecan indeed be coerced to aSystem.DateTime, but your original question did not tell us that.For more information on using
DataReaders, consult MSDN.