简体   繁体   中英

SQL Server 2008 : Varchar to Datetime conversion

I have a datetime column ArrivalDateTime which is stored as a varchar value.

Let's say if the value is 20161212093256 , I want the output to be 2016-12-12 09:32:56 .

I could get the date part in datetime format as below.

SELECT 
    CONVERT(DATETIME2(0), LEFT('20161212093256', 8))

This returns the output as 2016-12-15 00:00:00 .

I tried the following query to get the time part as well.

SELECT 
    CONVERT(DATE, LEFT('20161212093256', 8)) + ' ' + 
    CONVERT(TIME, RIGHT('20161212093256', 6))

But this throws an error:

The data types date and varchar are incompatible in the add operator

How can I get both date and time part in datetime format?

Get the date component first and convert it to DATETIME and then get the time component and convert it to DATETIME also. Finally, add the two results:

SELECT 
    CONVERT(DATETIME,LEFT('20161212093256', 8)) +
    CONVERT(DATETIME,
        LEFT(RIGHT('20161212093256', 6), 2) + ':' +
        SUBSTRING(RIGHT('20161212093256', 6), 3, 2) + ':' +
        RIGHT(RIGHT('20161212093256', 6), 2)
    )

To further explain, the result first conversion is the date component:

2016-12-12 00:00:00.000

The second conversion is the time component, but when you convert it to DATETIME it adds it to the 0 date or '1900-01-01' , so the result is:

1900-01-01 09:32:56.000

Then, you add both DATETIME s to get:

2016-12-12 09:32:56.000

To get rid of the ms component:

SELECT 
    CONVERT(DATETIME,LEFT('20161212093256', 8)) +
    CONVERT(DATETIME,
        LEFT(RIGHT('20161212093256', 6), 2) + ':' +
        SUBSTRING(RIGHT('20161212093256', 6), 3, 2) + ':00'
    )

Try this,

DECLARE @V_STR VARCHAR(20) = '20161212093256'
SELECT  CONVERT(SMALLDATETIME,LEFT(@V_STR,8) +' '+      --date
                SUBSTRING(@V_STR,9,2)+':'+              --hour
                SUBSTRING(@V_STR,11,2)+':'+             --minute
                SUBSTRING(@V_STR,13,2)) AS  DATE_TIME   --second

Try this

select concat(CONVERT(DATE, LEFT('20161212093256', 8)) , ' ' , CONVERT(TIME,  substring(RIGHT('20161212093256', 6),1,2)+ ':'  + substring(RIGHT('20161212093256', 4),1,2) + ':' +RIGHT('20161212093256', 2)))

above will display time with miliseconds, below without miliseconds

select concat(CONVERT(DATE, LEFT('20161212093256', 8)) , ' ' , substring(RIGHT('20161212093256', 6),1,2)+ ':'  + substring(RIGHT('20161212093256', 4),1,2) + ':' +RIGHT('20161212093256', 2))
SELECT STUFF(STUFF(STUFF(STUFF(STUFF('20161212093256', 5, 0, '-'), 8, 0, '-'), 11, 0, ' '), 14, 0, ':'), 17, 0, ':')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM