Convert 14 Char String to Datetime

Dom 771 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?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,351 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,600 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,491 Reputation points
    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