Reputation: 237
How do I check if a date string is in the MM/DD/YYYY format in SQL Server?
Upvotes: 6
Views: 69241
Reputation: 1479
you convert date to datestring in this format MM/DD/YYYY using CONVERT function
select convert(varchar(10),getdate(),101)
The output will be as of Sept 8th 2012
09/08/2012
There is no need to validate, other then checking the date field is null or not
Upvotes: 3
Reputation: 280252
SET DATEFORMAT MDY;
SELECT CASE WHEN ISDATE(@string) = 1
AND @string LIKE '[0-1][0-9]/[0-3][0-9]/[1-2][0-9][0-9][0-9]'
THEN 1 ELSE 0 END;
If the result is 1, it's a valid date, but there's no guarantee that it's the date the user meant. If they enter:
06/07/2012
There is no way to know if they meant June 7 or July 6. Your best bet is to make users pick dates from drop-downs or calendar controls, which allows you to control the format and avoid any needless interpretation. Your application layer can use strongly typed variables / parameters and insert into properly typed columns.
Upvotes: 17
Reputation: 17354
You have to do it outside the database. A database stores datetime internally in its own format. I dont think you can read what format the date is stored in. You can read it which ever way you like, for example dd/mm/yyyy or yyyy/mm/dd etc.
What you can do is check this value outside the database for any date field. You can use regular expression for that. But that will be outside the database.
Upvotes: 0
Reputation: 3360
If you're after the SQL Server dateformat to see whether it's MDY then use:
dbcc useroptions
And have a look at the dateformat Set Option
Upvotes: 4