Red Swan
Red Swan

Reputation: 15545

What is standard way to handle Null dates in .NET

I have asp.net form with C#, where is I am taking user information to insert in the database as usual by using Linq. well. Where as I am taking Date of birth also from the user, but if user skip to fill date text box from ui, then I am getting date like '01/01/0001' something like this, which certainly database security would not allow to store it.

So I need to check somewhere in my code that it is null or in this (above given) format. If it is null or in format '01/01/0001' then what exactly I have to do? I don't have any default value for dates.

So what is the standard way to handle if date is null (but not mandatory).Please guide me. So many times I found myself in trap while handling null for various types.

Edited see what i did seems it working here. but i don't think so this is standard way:

DateTime? otxtDOB = new DateTime();
                    if (!string.IsNullOrEmpty(DOB))
                    {
                    if (Convert.ToDateTime(DOB) != DateTime.MinValue)
                        {
                        otxtDateOfPurchese = Convert.ToDateTime(Convert.ToDateTime(DOB).ToString("dd-MMM-yyyy"));
                        }
                    else
                    {
                     otxtDOB = null;
                        }

                    }

Please confirm me is this right way ?

Upvotes: 6

Views: 28426

Answers (7)

vish
vish

Reputation: 1

obj.BirthDate = Convert.ToDateTime(string.IsNullOrEmpty(txtBirthDate.Text.ToString()) ? System.Data.SqlTypes.SqlDateTime.MinValue.Value : Convert.ToDateTime(txtBirthDate.Text.ToString()));

Upvotes: 0

user240141
user240141

Reputation:

use

DateTime dt; 
if(DateTime.TryParse(DatetImeValue.Tostring(),dt))   // datetimevalue is your db value
{
     datetimeproperty = dt;   // in your class declare it as DateTime? datetimeproperty 
}
else
{
    datetimeproperty = null;
}

While displaying check for null, if its null set it empty.

[Update]

Do one thing, Keep the property nullable. In your database. Set field to allow null and in the parameter user @DateTimeParam = null.

OR A QUICK WORKAROUND MAKE THE DATABASE FIELD AND PARAMETER VARCHAR INSTEAD OF DATETIME, IN PARAMETER PASS DATETIMEVALUE.TOSHORTDATESTRING() AND ALSO CHECK IF USER SKIPS PUT STRING.EMPTY IN PARAMETER. IN THIS MANNER IT WILL BE EASY TO YOU TO DISPLAY DATE AND TIME. YOU NEED NOT CAST OR WIPE OFF THE TIME PART IF YOU DO NOT NEED IT

Upvotes: 0

Mikael Östberg
Mikael Östberg

Reputation: 17146

You have the option of using Nullable<DateTime> (alias DateTime?). This makes you able to handle the date as null throughout your application.

However, personally I am not to found of nullables and would prefer this second path: You can use DateTime.MinValue (which is 01/01/0001) as a meaningful constant in your application and the check for DateTime.MinValue in your data access layer.

The database, if it is an SQL Server and the field is of type smalldatetime, would overflow and throw an exception if you tried to save DateTime.MinValue. Null however, may well be stored in the database for any type.

This is how you can parse your strings into nullable types:

private delegate bool TryParseDelegate<T>(string s, out T t);
private static T? TryParseNullable<T>(string s, TryParseDelegate<T> tryParse) where T : struct
{
   if (string.IsNullOrEmpty(s))
       return null;
   T t;
   if(tryParse(s, out t))
      return t;
   return null;
}

with usage:

var nullableDateTime = TryParseNullable<DateTime>("01/01/0001", DateTime.TryParse);

Upvotes: 0

ankur
ankur

Reputation: 4733

you can do some thing like this C# have some features like nullable type you can make use of this it will save you some piece of code it will be more robust too.

Public int InsertData(int? ouId)
{

chkValue = ouId.HasValue ? ouId.Value : 0;
} 

Upvotes: 0

Massif
Massif

Reputation: 4433

Making the date property Nullable (i.e. a "DateTime?") should allow it to actually be null if the user hasn't set it. (And provided your database column will allow nulls, it can be stored as null in the database)

Otherwise it's going to default to DateTime.MinValue which is what you're seeing here. And you'll have to explicity test for DateTime.MinValue when adding to the database.

Upvotes: 13

Jonathan
Jonathan

Reputation: 12025

DateTime is a value type (like a number), so you can't assing a null value to it. Mane people use DateTime.MinValue or DateTime.MaxValue instead, but I prefer to use nullable types:

DateTime? nullableDate;
dateSample.Value = null;

Upvotes: 0

Naveed Butt
Naveed Butt

Reputation: 2901

You can use this while passing to database.

object datetimeObj = null;
if (datetimefromUI == DateTime.MinValue) // This is put in the DateTime object by default
    datetimeObj = DBNull.Value;
else
    datetimeObj = datetimefromUI;

// Post datetimeObj to parameter in database...

Upvotes: -2

Related Questions