Ousman Ahmad
Ousman Ahmad

Reputation: 399

Convert Datetime to Unix timestamp

In Microsoft SQL Server 2012 or above, is it possible to convert a datetime value to Unix time stamp in a single select statement? If so, how can it be done?

Upvotes: 26

Views: 92877

Answers (3)

Ramil Gilfanov
Ramil Gilfanov

Reputation: 592

my function with localization

CREATE FUNCTION UNIX_TIMESTAMP(@ctimestamp datetime)
RETURNS integer
AS
begin
  return DATEDIFF(second,'1970-01-01',GETUTCDATE())+datediff(second,GETDATE(),@ctimestamp)
end

then i use value in js code

new Date(unixSec*1000)

Upvotes: 0

Aleksandr
Aleksandr

Reputation: 41

maybe this answer will help someone... If you have a problem when you try to convert datetime using datediff function to number of seconds (mssql message: The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.) then use:

select cast(datediff(d,'1970-01-01',@d1) as bigint)*86400+datediff(s,dateadd(day, datediff(day, 0, @d1), 0),@d1)

if you have ms sql server 2016+ use DATEDIFF_BIG function

Upvotes: 4

khaled4vokalz
khaled4vokalz

Reputation: 958

As Peter Halasz mentions in T-SQL DateTime to Unix Timestamp:

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

Try it out now like below @O A:

SELECT UNIX_TIMESTAMP(GETDATE());

Upvotes: 53

Related Questions