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

前端 未结 8 1313
执念已碎
执念已碎 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:02

    This function returns the unix time:

    alter FUNCTION [dbo].[GETTICKS] (@datetime datetime)
    RETURNS bigint
    WITH SCHEMABINDING
    AS
    BEGIN 
        RETURN 
            DATEPART(millisecond,@datetime) +
            CONVERT(bigint, 
                        1000 * (
                            DATEPART(second,@datetime) +
                            60 * DATEPART(minute,@datetime) +
                            3600 * DATEPART(hour,@datetime) +
                            3600 * 24 * DATEPART(DAYOFYEAR,@datetime) +
                            convert(bigint, 3600 * 24 * (((DATEPART(year,@datetime) - 1970) * 365) + ((DATEPART(year,@datetime) - 1972) / 4)))
                    ) )
    END
    

提交回复
热议问题