2

I need to cast string values of the following formats to DateTime:

2042-04
2011-01

Is there an easy way to do this? I've tried CAST AND CONVERT without much luck.

Thanks!

0

4 Answers 4

6

try appending "-01" to the end of it and then doing the cast or convert

Sign up to request clarification or add additional context in comments.

Comments

2
declare @S varchar(7)
set @S = '2042-04'

select cast(stuff(@S, 5, 1, '')+'01' as datetime)

YYYYMMDD is a safe format regardless of SET DATEFORMAT. YYYY-MM-DD is not. http://www.sommarskog.se/wishlist.html#YYYYMMDD

Comments

0
SELECT CAST('2011-01-01' AS DATETIME)
SELECT CONVERT(DATE , '2011-01-01')

It seems you need to add a 'day' to the string.

Comments

0
Declare @Table Table
(
    ColDateTime Varchar(100)
)
Insert into @Table
Select '2042-04' UNION ALL
Select '2011-01'

Select ColDateTime As VarcharCol,
Cast(
    substring(ColDateTime,0,charindex('-',ColDateTime))+substring(ColDateTime,charindex('-',ColDateTime)+1,len(ColDateTime))+'01'
As DateTime) As DateTimeCol
from @Table

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.