Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datetime issue with 01/01/1900

i have a datetime column in sql server and its optional field and if the user decided not to enter then i want to insert the value as NULL in the table and i define something like this:

@deadlineDate datetime = null

when i am inserting into sql server i have this code in asp.net

private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return null;
    }
    return getDeadlineDate.Value;

}

but the problem is: its inserting

1900-01-01 00:00:00.000

in the sql table instead of NULL

what i am doing wrong here?

UPDATE:

private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return DBNull.Value; //throws error....
    }
    return getDeadlineDate.Value;          
}
like image 420
Nick Kahn Avatar asked Aug 19 '10 14:08

Nick Kahn


2 Answers

You need DBNull.Value rather than null when inserting into SQL server.

When you set DateTime = null in .NET it takes the minimum value of DateTime which is 01-01-0001.

I'd assume you are using a SMALLDATETIME in SQL Server where the minimum value is '01/01/1900'

like image 91
Chris Diver Avatar answered Sep 30 '22 05:09

Chris Diver


Assuming you have:

DateTime? date = GetDate();
command.Parameters.Add("@date").Value = date;

in case when date == null you want to insert SQL NULL i.e. DBNull.Value so you should do next:

DateTime? date = GetDate();
command.Parameters.Add("@date").Value = (object)date ?? DBNull.Value;

which means the same as:

if(date != null)
     // use date
else
     // use DBNull.Value

if you want to take care about nullable datetime in your function you should declare it next way:

private object GetDate()
{
    DateTime date;
    return DateTime.TryParse(selectedDate, out date) ? date : DBNull.Value;
}

command.Parameters.Add("@date").Value = GetDate();

but I don't recommend to do that and use next:

command.Parameters.Add("@date").Value = (object)GetDate() ?? DBNull.Value;
like image 38
abatishchev Avatar answered Sep 30 '22 06:09

abatishchev