0

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

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Henry
  • 167
  • 1
  • 10

3 Answers3

1

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]
Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36
  • I am using SQLServer 2014, I want to update my table. update copy_vw_work_in_progress_so_list Set picking_datetime = CAST(FORMAT([picking_date],'####-##-## ##:##:##') as datetime). and error Msg 8116, Level 16, State 1, Line 9 Argument data type nvarchar is invalid for argument 1 of format function. – Henry Jun 14 '16 at 02:44
  • See my update. `...CAST(FORMAT(cast([picking_date] as bigint),'####-##-## ##:##:##') as datetime)...` – Alex Kudryashev Jun 14 '16 at 02:46
0

Hmmm. I don't think there is a really clean way, but something like this should work:

select (convert(datetime, left(col, 8) as datetime) +
        convert(datetime, convert(time,
                                  stuff(stuff(right(col, 6), 5, 0, ':'), 3, 0, ':')
                                 )
                )
        )
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Maybe you can try in this way, for example Date is the column of your table, 103 is the format of Date you want to convert, google for more details.

CONVERT(datetime, Date, 103)
120196
  • 283
  • 6
  • 14
  • I've already tried but get error Conversion failed when converting date and/or time from character string. – Henry Jun 14 '16 at 02:26