Search code examples
sqlsql-serversql-server-2008unix-timestamp

UNIX_TIMESTAMP in SQL Server


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


Solution

  • If you're not bothered about dates before 1970, or millisecond precision, just do:

    -- SQL Server
    SELECT DATEDIFF(s, '1970-01-01 00:00:00', DateField)
    

    Almost as simple as MySQL's built-in function:

    -- MySQL
    SELECT UNIX_TIMESTAMP(DateField);
    

    Other languages (Oracle, PostgreSQL, etc): How to get the current epoch time in ...


    If you need millisecond precision (SQL Server 2016/13.x and later):

    SELECT DATEDIFF_BIG(ms, '1970-01-01 00:00:00', DateField)