Minimum & Maximum Dates in code

When updating Sql columns that need a minimum or maximum date, consider using the defaults from the System.Data.SqlType namespace:

   1:  DateTime minDate = SqlDateTime.MinValue.Value
<pre><span class="lnum">   2:  </span>&#160;</pre>

<pre class="alt"><span class="lnum">   3:  </span><span class="rem">// and</span></pre>

<pre><span class="lnum">   4:  </span>&#160;</pre>

<pre class="alt"><span class="lnum">   5:  </span>DateTime maxDate = SqlDateTime.MaxValue.Value</pre>

This can be a lot safer than putting hard-coded "magic date" constants in your code.

2 Comments

  • This is new to me. What is the difference/benefit of this versus DateTime.MinValue and DateTime.MaxValue?

    Thanks

  • DateTime.MinValue represents a range from 01/01/0001 to 12/31/9999, which is outside of the range 01/01/1753 to 12/31/9999 supported by Sql Server. So, if you try to insert/update a column value to DateTime.MinValue you will get an overflow error.

    The nice thing about using default ranges & values provided by the System.Data.SqlType namespace is that if Microsoft decides to change these ranges in Sql Server later, they will likely update the corresponding SqlTypes within the framework.

    Of course, if you are using data access code that works against multiple database engines (e.g. Oracle, DB2, MySql), you may want to create a facade for such defaults so you can switch the default values to something other than SqlDateTime.MinValue & MaxValue.

Comments have been disabled for this content.