Rugven Jag
Rugven Jag

Reputation: 29

Convert varchar datetime without dashes and colon to varchar datetime with dashes and colon

I want to convert this 20201001163318 varchar date & time to something like this 2020-10-01 16:33:18.

I tried this

select convert(varchar, getdate(), 25) 

but it does not work

Upvotes: 1

Views: 762

Answers (1)

John Cappelletti
John Cappelletti

Reputation: 81960

Perhaps stuff() in concert with a try_convert()

Example

declare @S varchar(50) = '20201001163318'

Select try_convert(varchar(19),try_convert(datetime,stuff(stuff(stuff(@S,13,0,':'),11,0,':'),9,0,' ')),120)

Returns

(No column name)
2020-10-01 16:33:18

Also if you wanted to convert getdate() to a string, you could try:

Select convert(varchar(19),getdate(),120)

Upvotes: 1

Related Questions