Validating a date to be within the SqlDbType.DateTime range
Asked Answered
J

3

7

I want to validate a System.DateTime value before I add it as a parameter to my 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?

Jeaninejeanlouis answered 2/11, 2010 at 18:56 Comment(0)
C
21

What about SqlDateTime.MinValue and SqlDateTime.MaxValue?

Note: these are SQL type min/max not the .net types like the previous 2 answers :-)

Cat answered 2/11, 2010 at 19:0 Comment(3)
+1 - that looks like it is exactly what the OP is looking for.Turino
Eyes are going bad this late in the afternoon. My mistake.Wildfire
To expand upon this, if you need to check a regular DateTime (something I've stumbled upon), remember that SqlDateTimes expose a Value property, which is a DateTime.Repeal
E
0
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.

Eldrid answered 2/11, 2010 at 18:59 Comment(0)
N
-6

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.

Neptunian answered 2/11, 2010 at 19:0 Comment(3)
For some of us, it's easy to make a typo in a date. Or to misunderstand the date format (mm/dd/yyyy or dd/mm/yyyy).Eldrid
Give them a date picker and disable the textbox. That's how I roll... :-)Neptunian
what about the birthday of ancient peopleOverscrupulous

© 2022 - 2024 — McMap. All rights reserved.