What is standard way to handle Null dates in .NET

26,285

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.

Share:
26,285
Red Swan
Author by

Red Swan

Updated on July 10, 2022

Comments

  • Red Swan
    Red Swan almost 2 years

    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 ?