Convert 14 Char String to Datetime

Dom 941 Reputation points
2024-04-06T15:15:48.1066667+00:00

I have a field in a table called TraceID that stores data like this:

2024040611102200021

The first 8 characters represent the date (YYYYMMDD). The next 6 characters represent the time (HHMMSS). The last five are insignificant numbers. So this would be 04.06.2024 @ 11:10:22 (AM).

I create the representation of the timestamp: LEFT(TraceID,14) as TStamp

How can I now convert this string to a datetime type?

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2024-04-06T20:36:48.5866667+00:00

    simple:

    declare @d varchar(20) = '2024040611102200021'
    select cast(SUBSTRING(@d,1,4) + '-' + SUBSTRING(@d,5,2) + '-' + SUBSTRING(@d,7,2) 
                + 'T' 
                + SUBSTRING(@d, 9,2) + ':' + SUBSTRING(@d, 11,2) + ':' + SUBSTRING(@d, 13,2) 
            as datetime)
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.