将 16 位日期时间字符串转换为带微秒的日期时间

Convert 16-digit datetime string to datetime with microseconds

我正在尝试将 SQL 服务器中的 16 位日期时间字符串(带毫秒)转换为实际的日期时间和毫秒。一个示例是更改这样的记录 2022020804180454,以读取 02/08/2022 04:18:04.54.

的美国日期时间

我该怎么做? Google/Bing 搜索表明日期带有午夜时间戳

CONVERT(datetime, CAST('2022020804180454' AS CHAR(8)), 101)

这不是我想要的。

任何帮助或被指出正确的方向都会有所帮助。

注入需要的字符,STUFF,然后然后转换:

SELECT CONVERT(datetime2(2),STUFF(STUFF(STUFF(STUFF(V.YourDateString,15,0,'.'),13,0,':'),11,0,':'),9,0,' '))
FROM (VALUES('2022020804180454'))V(YourDateString);

您可以使用方便的 DATETIMEFROMPARTS:

DECLARE @s nvarchar(16) = '2022020804180454';


SELECT DATETIMEFROMPARTS(LEFT(@s,4), --year
                         SUBSTRING(@s,5,2), --month
                         SUBSTRING(@s,7,2), --day
                         SUBSTRING(@s,9,2), --hour
                         SUBSTRING(@s,11,2), --minute
                         SUBSTRING(@s,13,2), --second
                         SUBSTRING(@s,15,2)*10 --millisecond
                         )