0

I have string date in yymmdd format, for example 150202

I want to convert this string into a valid date in format yyyymmdd, e.g. 20150202.

Thanks in advance.

5
  • 4
    how will you decide it's 2015 or 1915? Commented Feb 13, 2015 at 7:28
  • Have you made some research before asking? Tested some code? This is a really common question and you have lot of samples here in SO. Commented Feb 13, 2015 at 7:28
  • 1
    SQL Server DATE or DATETIME2(n) don't have any format associated with them - they're stored in binary bytes Commented Feb 13, 2015 at 7:30
  • 1
    Stroing date's as string is a bad practice .. you can read more here:sqlblog.org/2009/10/12/… Commented Feb 13, 2015 at 7:33
  • 1
    I agree with @Deepshikha. If you known that 150202 means 20150202 just concat "20" and "150202" and than convert this string into date format Commented Feb 13, 2015 at 7:39

3 Answers 3

2

convert your string to datetime and then do that you want with it

declare @dt varchar(6) = '150213'
select CONVERT(datetime, @dt, 112)

Do another CONVERT to transform it to yyyymmdd format.

SELECT CONVERT(VARCHAR(10), CONVERT(DATETIME, @dt, 112), 112)
Sign up to request clarification or add additional context in comments.

7 Comments

Did you test it? The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
@wewesthemenace: works just fine for me (SQL Server 2014 - US English language)
@wewesthemenace, i improved my answer, i used 'yyddmm' format for string. it is 'yymmdd' now
@marc_s, it's 151302 before the edit. @Ash, thanks!
@mohan111, it is coming as varchar and output is datetime, which can be displayed in many formats
|
0

may this will work

select CONVERT(datetime, '150202', 112)

for all date conversions

http://www.sqlusa.com/bestpractices/datetimeconversion/

Comments

0

instead of select CONVERT(datetime, '150202', 112) its better to use "select TRY_CONVERT(datetime, '150202', 112)" while using try_convert if there is any error it will returns null,if we are using convert it will returns error when conversion fails.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.