I tried this

SELECT convert(datetime, '23/07/2009', 111) 

but got this error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

However

SELECT convert(datetime, '07/23/2009', 111) 

Is OK though

How to fix the 1st one?

7

7 Answers

The last argument of CONVERT seems to determine the format used for parsing. Consult MSDN docs for CONVERT.

111 - the one you are using is Japan yy/mm/dd.

I guess the one you are looking for is 103, that is dd/mm/yyyy.

So you should try:

 SELECT convert(datetime, '23/07/2009', 103) 
1

Try:

SELECT convert(datetime, '23/07/2009', 103) 

this is British/French standard.

0
SELECT COALESCE(TRY_CONVERT(datetime, Value, 111), TRY_CONVERT(datetime, Value, 103), DATEADD(year,-1,GetDate())) 

You could add additional date formats as the Coalesce will go through each until it returns a successful Try_Convert

1
SELECT convert(varchar(10), '23/07/2009', 111) 
0

SQL Server by default uses the mdy date format and so the below works:

SELECT convert(datetime, '07/23/2009', 111) 

and this does not work:

SELECT convert(datetime, '23/07/2009', 111) 

I myself have been struggling to come up with a single query that can handle both date formats: mdy and dmy.

However, you should be ok with the third date format - ymd.

1
SELECT convert(datetime, '23/07/2009', 103) 

You can convert a string to a date easily by:

CAST(YourDate AS DATE) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy