Home > MS SQL Server, Transact-SQL, TSQL > T-SQL DateTime to Unix Timestamp

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());

  1. None
    September 7, 2011 at 11:36 am | #1

    Nice! Thanks

  2. Simon
    September 15, 2011 at 2:05 am | #2

    You may need to call the function with dbo.
    E.g. SELECT dbo.UNIX_TIMESTAMP(GETDATE())

    • September 15, 2011 at 7:46 pm | #3

      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.

  3. Leonardo Mendez
    March 28, 2012 at 7:19 pm | #4

    Wonderful!! Many thanks

  1. May 29, 2012 at 7:32 am | #1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.