Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nullable DateTime out of the database

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];
like image 573
pikachu Avatar asked Feb 29 '12 17:02

pikachu


People also ask

Can DateTime be nullable?

DateTime itself is a value type. It cannot be null.

Can DateTime be null in SQL?

Using a DateTime column in an SQL table is quite common. Using it in . Net has one limitation – DateTime cannot be null as it is a struct and not a class.

What is a nullable in database?

A null value in a relational database is used when the value in a column is unknown or missing. A null is neither an empty string (for character or datetime data types) nor a zero value (for numeric data types).

How do you define a nullable in SQL?

The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that appears to be blank. A field with a NULL value is a field with no value. It is very important to understand that a NULL value is different than a zero value or a field that contains spaces.


Video Answer


3 Answers

A SQL null is not the same as a .NET null; you have to compare against System.DBNull.Value:

object sqlDateTime = sqldatareader[0];
DateTime? dt = (sqlDateTime == System.DBNull.Value)
    ? (DateTime?)null
    : Convert.ToDateTime(sqlDateTime);

In answer to your comment, the data type of the Item property of a DataReader is that of the underlying database type. It could be System.Data.SqlTypes.SqlDateTime for a non-null SQL Server database, or System.DBNull for a null column, or System.Data.Odbc.OdbcTypes.SmallDateTime for an ODBC database, or really just about anything. The only thing you can rely on is that it is of type object.

This is also why I suggest using Convert.ToDateTime() instead of type coercion to DateTime. There is no guarantee a ODBC or whatever date column can be coerced to a .NET DateTime. I note your comment specifies a "sqldatareader", and a SQL Server System.Data.SqlTypes.SqlDateTime can indeed be coerced to a System.DateTime, but your original question did not tell us that.

For more information on using DataReaders, consult MSDN.

like image 149
Dour High Arch Avatar answered Oct 18 '22 17:10

Dour High Arch


I recently found this trick, it's simple:

var dt = sqldatareader[0] as DateTime?;
like image 32
pikachu Avatar answered Oct 18 '22 19:10

pikachu


how about creating helper method

private static DateTime? MyDateConverter(object o)
{
    return (o == DBNull.Value || o == null) ? (DateTime?)null : Convert.ToDateTime(o);
}

Usage

MyDateConverter(sqldatareader[0])
like image 3
Usman Ali Avatar answered Oct 18 '22 19:10

Usman Ali