UNIX_TIMESTAMP in SQL Server

后端 未结 8 1953
陌清茗
陌清茗 2020-12-01 15:45

I need to create a function in SQL Server 2008 that will mimic mysql\'s UNIX_TIMESTAMP().

Thanks in advance !

相关标签:
8条回答
  • 2020-12-01 16:46

    Sql Server 2016 and later have a DATEDIFF_BIG function that can be used to get the milliseconds.

    SELECT DATEDIFF_BIG(millisecond, '1970-01-01 00:00:00', GETUTCDATE())
    

    Create a function

    CREATE FUNCTION UNIX_TIMESTAMP()
        RETURNS BIGINT
    AS
    BEGIN
        RETURN DATEDIFF_BIG(millisecond, '1970-01-01 00:00:00', GETUTCDATE())
    END
    

    And execute it

    SELECT dbo.UNIX_TIMESTAMP()
    
    0 讨论(0)
  • 2020-12-01 16:46

    For timestamp with milliseconds result I found this solution from here https://gist.github.com/rsim/d11652a8336137832df9:

    SELECT (cast(DATEDIFF(s, '1970-01-01', GETUTCDATE()) as bigint)*1000+datepart(ms,getutcdate()))
    

    Answer from @Rafe didn't work for me correctly (MSSQL 20212) - I got 9 seconds of difference.

    0 讨论(0)
提交回复
热议问题