Checking DateTime for null?

joe_pool_is

Contributor
Joined
Jan 18, 2004
Messages
507
Location
Longview, TX [USA]
How do I check for an uninitialized DateTime?

If I start my code by simply declaring a DateTime value:

DateTime time1;

Then the compiler gives me the error that the field was uninitialized.

Seting the DateTime value to null is not legal though, it seems:

DateTime time1 = null;

How am I supposed to be initializing a DateTime value?
 
Some of you may be wondering, "Why would you want a null DateTime?"

Here's an example of somewhere that I have to initialize the DateTime object with data that is *not* what I want:
Code:
/// <summary>
/// Synchronize the Time on the SQL Server with the time on the device
/// </summary>
private void SyncWithSqlTime(DateTime sqlTime) // pass in or query for time to set on device
{
  SYSTEMTIME st = new SYSTEMTIME();
  sqlTime = DateTime.Now; // checking to see if sqlTime has been set doesn't seem possible
  m_lastError = string.Empty;
  try
  {
    m_db.Open(); // Sql Connection object
    using (SqlCommand cmd = new SqlCommand("SELECT GetDate() AS [CurrentDateTime]", m_db))
    {
      SqlDataReader r = cmd.ExecuteReader();
      while (r.Read() == true)
      {
        sqlTime = (DateTime)r["CurrentDateTime"];
      }
    }
  }
  catch (InvalidOperationException e)
  {
    Console.WriteLine(e.StackTrace);
  }
  catch (SqlException e)
  {
    Console.WriteLine(e.StackTrace);
  }
  finally
  {
    m_db.Close();
  }
  st.FromDateTime(sqlTime); // Convert to SYSTEMTIME
  SetLocalTime(ref st); // PInvoke Win32 API to set time
}
 
Nullable types

If using .NET 2 or later, you can use nullable types:

C#:
DateTime? sqlTime = null;

Alternatively, I tend to initialize variables to something like DateTime.MinValue and then test for that.

Good luck :cool:
 
Re: Nullable types

Thanks, MrPaul.

I'd seen variables declared using a Question Mark (?) before, but I had no idea what they were called, so there was no way to look them up.

Now, I know how to set a DateTime to a null value, and I know what the Question Mark means! I got a 2-for-1!
 
Back
Top