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

前端 未结 8 1280
执念已碎
执念已碎 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 22:07

    I was missing a millisec-accurate one-liner solution to this question, so here is one:

    SELECT ROUND(CAST(CAST(GETUTCDATE() AS FLOAT)*8.64e8 AS BIGINT),-1)*1000+599266080000000000
    

    8.64e8 = TimeSpan.TicksPerDay / 1000
    599266080000000000 = DateTime.Parse('1900-01-01').Ticks

    This works for the DATETIME type but not for DATETIME2. The 4/3 ms resolution of DATETIME makes it necessary to involve ROUND(…,-1): after the multiplication by 8.64e8 the float result always ends with either 0 or 33.3 or 66.6. This gets rounded to 0, 30 or 70.

提交回复
热议问题