I want to validate a System.DateTime value before I add it as a parameter to 开发者_StackOverflowmy SqlCommand instance.
The MSDN documentation for the SqlDbType enumeration says:
Date and time data ranging in value from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds.
To validate the value, I'm using
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 min and max values?
What about SqlDateTime.MinValue and SqlDateTime.MaxValue?
Note: these are SQL type min/max not the .net types like the previous 2 answers :-)
SqlDateTime.MaxValue = 12/31/9999
SqlDateTime.MinValue = 1/1/1753
Your code would then read:
if (value < SqlDateTime.MinValue || value > SqlDateTime.MaxValue)
I think this meets your needs better than DateTime.MaxValue
and DateTime.MinValue
, because DateTime.MinValue
is not 1/1/1753 but rather is 1/1/0001.
I think the real question is why is your users entering dates outside of this range? Your code to validate it is fine, however I'd suggest it's a larger problem in the UI where people can enter bogus dates.
精彩评论