Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What is the default value of a datetime variable?

Status
Not open for further replies.

j9

Programmer
Jun 6, 2001
90
0
0
US
I know that a string variable defaults to null and an integer defaults to zero if you don't assign values, but what is the default for a datetime variable? I need to check the value to see if it's 'blank' so that I know to insert dbnull.value into the database. Currently, my workaround for a conditional statement is:

if(myDate.Ticks != 0)
...
 
What you might try doing is creating an initialized DateTime just for the sake of comparison:

Code:
DateTime dtmBlank;

if (myDate != dtmBlank)
...

If you get a compiler error that says "use of unassigned something or other...", you probably can't have an unintialized DateTime. In that case, this will create a DateTime based on the current system time which is unfortunately not reproduceable:

Code:
DateTime dtmBlank = new DateTime();
 
That is true about integer and string and other value types but you should initialize such variable in order to use.
When you declare :
Code:
int myInt;
DateTime myDate;
these variable are unusable until you initialize.
If you declare:
Code:
int myInt=new int();
DateTime myDate = new DateTime();
In this case myInt is 0 and myDate is a structure set to 1/1/1 12:00:AM.
obislavu

 
From MSDN,
Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead, every struct implicitly has a parameterless instance constructor that always returns the value that results from setting all value type fields to their default value and all reference type fields to null
so obislavu is correct, and using
Code:
DateTime dtmBlank = new DateTime();
does give a reproducible result.
 
You might want to try something similar to the following:

DateTime myDate = DateTime.MinDate;

....................

if(myDate != DateTime.MinDate)
{
//Save value to DB
}
else
{
//Save null to DB
}

You might need to check the syntax here as i've not had to do this for about a month but I find this workls pretty well for me.

HTH

Smeat
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top