Dattu
Dattu

Reputation: 31

Datatype Datetime value Initialization

I am updating the a table with different values and in that one date datatype also there.

After updating the table I am initializing the variables to 0 and spaces based on the datatypes - but I am unable to initialize Datetime Datatype.

How can I do this in C#?

Upvotes: 3

Views: 10393

Answers (4)

Chris Catignani
Chris Catignani

Reputation: 5306

This question is a little old...but still relevant. Creating a new DateTime variable

DateTime dDate = new DateTime();

will give it an initial value of {1/1/0001 12:00:00 AM}...which may be what you want.
MSSQL will give you a range error if dates are outside the range of January 1, 1753, through December 31, 9999 datetime TSQL
In the case of database data...I think a null date is better than a wrong date.
Anyway...one way to initialize a date to a value is simply:

DateTime dDate = new DateTime(1980,01,01);

All kinds of overloads on this:DateTime Struct

Upvotes: 0

Naha
Naha

Reputation: 536

Set the DateTime to null with this code:

DateTime? datetime;

Since DateTime is a struct, not a class, you get a DateTime object, not a reference, when you declare a field or variable of that type. And, in the same way as an int cannot be null, so can this DateTime object never be null, because it's not a reference.

Adding the question mark turns it into a nullable type, which means that either it is a DateTime object, or it is null.

Finally when using the value, assign the value to an DateTime:

if(datetime.hasvalue)
{    
DateTime dt = datetime.value;
}

Upvotes: 0

Jaroslav Jandek
Jaroslav Jandek

Reputation: 9563

You can initialize the values to default(type) implicitly - for DateTime: default(DateTime).

For database operations, you would probably be better of with the SqlDateTime type as the minimal or maximal values of DateTime usually cannot be stored in databases as date types.

Initialization:

string connString = "...";
string cmdText = @"INSERT INTO Test(col1, col2) VALUES (@col1, @col2)";
using (SqlConnection conn = new SqlConnection(connString))
{
    using (SqlCommand cmd = new SqlCommand(cmdText, conn))
    {
        cmd.Parameters.Add("@col1", SqlDbType.NVarChar).Value = ""; // or .Value=DBNull.Value;
        cmd.Parameters.Add("@col2", SqlDbType.DateTime).SqlValue = default(SqlDateTime); // or .Value=DBNull.Value;
    }
}

You can initialize all the values to DBNull.Value

Upvotes: 1

Aik
Aik

Reputation: 3738

You can get initialize value for every value type by "default" keyword

DateTime a = default(DateTime);

Upvotes: 7

Related Questions