T-SQL DateTime to Unix Timestamp
This is a really simple Transact-SQL function to make it easier to convert MS SQL’s datetime datatype to Unix Timestamps.
Converting a datetime to unix timestamp is easy, but involves error prone typing the following:
@timestamp=DATEDIFF(second,{d '1970-01-01'},@datetime)
Where @datetime is the datetime value you want to convert.
The {d ‘yyyy-mm-dd’} notation is an ODBC escape sequence.
The function:
CREATE FUNCTION UNIX_TIMESTAMP (
@ctimestamp datetime
)
RETURNS integer
AS
BEGIN
/* Function body */
declare @return integer
SELECT @return = DATEDIFF(SECOND,{d '1970-01-01'}, @ctimestamp)
return @return
END
That’s it :)
Try it out with:
SELECT UNIX_TIMESTAMP(GETDATE());
Categories: MS SQL Server, Transact-SQL, TSQL
DBMS, MS SQL, MS SQL Server, RDBMS, Transact-SQL

Nice! Thanks
You may need to call the function with dbo.
E.g. SELECT dbo.UNIX_TIMESTAMP(GETDATE())
Hello Simon,
During my tests when I first wrote this little script it worked without dbo.
There might be certain configurations where that would be necessary. Thank you for pointing this out.
Wonderful!! Many thanks