Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle null for a allow-null datetime field (DB) in our program?

Tags:

c#

datetime

null

How could we handle null for a datetime field (got from SQL Server) in our program in c#?

like image 315
odiseh Avatar asked Aug 29 '09 08:08

odiseh


People also ask

How do you handle null in DateTime?

The Nullable < T > structure is using a value type as a nullable type. By default DateTime is not nullable because it is a Value Type, using the nullable operator introduced in C# 2, you can achieve this. Using a question mark (?) after the type or using the generic style Nullable.

Can a DateTime field be null?

DateTime CAN be compared to null; It cannot hold null value, thus the comparison will always be false. DateTime is a "Value Type". Basically a "value type" can't set to NULL. But by making them to "Nullable" type, We can set to null.

Can DateTime be null in SQL?

Inserting a null value to the DateTime Field in SQL Server is one of the most common issues giving various errors. Even if one enters null values the value in the database is some default value as 1/1/1900 12:00:00 AM.

How do I insert a null into a date field?

"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);


2 Answers

There are 3 common approaches here;

  • if you are talking about object (perhaps as you fetch it from a data-reader), then DBNull.Value can represent null. I don't tend to let this out of the data-layer, though
  • due to .NET 1.1 history, DateTime.MinValue is commonly interpreted as null; a magic number, maybe - but it works and is supported by most data-binding etc
  • in .NET 2.0, Nullable<T> means you can use DateTime? - i.e. a nullable-of-DateTime; just use DateTime? where-ever you mean a DateTime that can be null, and you can give it a value of null or a valid DateTime.

Some other thoughts on data-access and nulls:

  • when passing to a SqlCommand you must use DBNull.Value, not null - see below
  • when reading from a data-reader, I tend to check reader.IsDbNull(ordinal)

command stuff (with Nullable<T> as the example):

param.Value = when.HasValue ? (object)when.Value : DBNull.Value;
like image 85
Marc Gravell Avatar answered Nov 03 '22 01:11

Marc Gravell


Use DateTime?

What problem are you having, specifically?

-- Edit

Just so it's clear, that's a Nullable DateTime object, not a question :)

DateTime? t = null;

-- Edit

Responding to comment, check it like so:

DateTime? theTime;

if( table["TheColumn"] == DBNull.Value ){
    theTime = null;
} else {
    theTime = (DateTime) table["TheColumn"];
}
like image 23
Noon Silk Avatar answered Nov 03 '22 00:11

Noon Silk