Henry Henry - 5 months ago 15
SQL Question

How to Convert nvarchar (including time) into datetime

I have data 20160526094432, and I want to convert into datetime in SQLServer
The result will be 2016-05-26 09:44:32

Is there simple way to do that ?

Thanks

Answer

If you use MS SQL Server 2012 or newer then you can enjoy format function.

select cast(format(20160526094432,'####-##-## ##:##:##') as datetime) [date-time]

If your long number is a string then you have to convert it.

declare @d varchar(20)='20160526094432'
select cast(format(cast(@d as bigint),'####-##-## ##:##:##') as datetime) [date-time]