Check Date Within SqlDbType.DateTime Range

I want to check the value of System.DateTime before adding it as a parameter to my SqlCommand instance.

The MSDN documentation for the SqlDbType enumeration states:

Date and time data from January 1, 1753 to December 31, 9999, accurate to 3.33 milliseconds.

To check the value, I use

public readonly DateTime SqlDateTimeMin = new DateTime(1753, 1, 1); public readonly DateTime SqlDateTimeMax = new DateTime(9999, 12, 31); if (value < SqlDateTimeMin || value > SqlDateTimeMax) // Validation check fails else // Validation check succeeds 

Is this the best way? Is there an alternative to hard coding these minimum and maximum values?

+6
c # datetime sql-server sqldbtype
source share
3 answers

What about SqlDateTime.MinValue and SqlDateTime.MaxValue ?

Note: this is the min / max SQL type, not the .net types, such as the previous 2 answers :-)

+19
source share
 SqlDateTime.MaxValue = 12/31/9999 SqlDateTime.MinValue = 1/1/1753 

Then your code will read:

 if (value < SqlDateTime.MinValue || value > SqlDateTime.MaxValue) 

I think this meets your needs better than DateTime.MaxValue and DateTime.MinValue , because DateTime.MinValue not 1/1/1753, but is 1/1/0001.

0
source share

I think the real question is why do your users enter dates outside this range? Your code for checking it is fine, however I would offer it a big problem in the user interface where people can enter dummy dates.

-4
source share

All Articles