Jason312
Jason312

Reputation: 193

How to convert integer into datetime in varchar format

I m getting this error when trying to convert below integer into datetime in a varchar format.

Conversion failed when converting date and/or time from character string

Code:

CONVERT(VARCHAR(MAX), CAST('200901041421' AS DATETIME))

Upvotes: 1

Views: 377

Answers (1)

S3S
S3S

Reputation: 25152

You need a space, and a colon. I'm not sure why you want to do this though... present the date in a format on your front end (presentation layer) and keep dates stored as dates or datetime in the database and you won't run into this issue :)

SELECT CONVERT(VARCHAR(MAX), CAST('20090104 14:21' AS DATETIME))

Also, no need to use MAX here. That's a waste of storage. Something like this makes more sense.

SELECT CONVERT(VARCHAR(24), CAST('20090104 14:21' AS DATETIME), 113)

Using a column name...

SELECT CONVERT(VARCHAR(24), CAST(YourColumnName AS DATETIME), 113)
FROM YourTable

You can see other conversions here

Upvotes: 1

Related Questions