Convert 14 Char String to Datetime

Dom 951 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
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Bruce (SqlWork.com) 81,356 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.

1 additional answer

Sort by: Most helpful
  1. Ramana Kopparapu 306 Reputation points
    2025-10-29T14:48:38.79+00:00

    We can also get the output with STUFF..

    DECLARE @str VARCHAR(14) = '2024040611102200021';

    SELECT CONVERT(datetime,

       LEFT(@str,8) + ' ' + 
    
       STUFF(STUFF(RIGHT(@str,6),3,0,':'),6,0,':'), 120);
    

    Output:

    2024-04-06 11:10:22.000

    0 comments No comments

Your answer

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