1

I know this has been asked several times but I haven't seen it asked for my particular situation.

If a text was in this format: Dec 30 2006 12:38AM Is there any way to convert this to an actual datetime. I am not excited about creating a function to parse this to a date using substrings, etc.

A previous developer developed the whole application and decided to store all the date values in the database as a VARCHAR which conveniently changed them from something like: 2016-12-30 00:38:00 to Dec 30 2006 12:38AM. This makes them non comareable (SMH)

3 Answers 3

1

Just use cast():

select cast('Dec 30 2006 12:38AM' as datetime)

Here is a SQL Fiddle.

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

3 Comments

perfect. Not sure why it never worked for me the 1st time
@logixologist Possibly because it's not language safe. Try set language french; first, for example.
@AaronBertrand . . . I'm amazed by how versatile cast()/convert() are when converting to dates. They understand all sorts of formats that are not otherwise easily parsable
1

--Please try this

declare @var varchar(30) = 'Dec 30 2006 12:38AM' select convert(datetime, @var)

Comments

1

Since you are converting strings (which is always risky), I would suggest try_convert() if 2012+. Try_Convert() will return a null if the conversion fails rather than throwing an error.

Example

Select ValidDate = try_convert(datetime,'Dec 30 2006 12:38AM')
      ,BogusDate = try_convert(datetime,'Not a Valid Date String')

Returns

ValidDate                BogusDate
2006-12-30 00:38:00.000  NULL

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.