Convert SQL Server DateTime object to BIGINT (.Net ticks)

前端 未结 8 1274
执念已碎
执念已碎 2020-12-08 21:38

I need to convert a DateTime type value to BIGINT type in .Net ticks format (number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001).<

8条回答
  •  [愿得一人]
    2020-12-08 21:55

    you can use below sql to convert a date or utcdate to ticks

    declare @date datetime2 = GETUTCDATE() or getdate()
    declare @dateBinary binary(9) = cast(reverse(cast(@date as binary(9))) as binary(9))
    declare @days bigint = cast(substring(@dateBinary, 1, 3) as bigint)
    declare @time bigint = cast(substring(@dateBinary, 4, 5) as bigint)
    
    select @date as [DateTime],  @days * 864000000000 + @time as [Ticks]
    

    and use below sql to convert the tick to a date

    SELECT Converted = CAST(635324318540000000/864000000000.0 - 693595.0 AS DATETIME)
    

提交回复
热议问题