Convert date and time to Unix

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

+9
source share
1 answer

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

Converting a date and time to a Unix timestamp is easy, but entails an error by typing the following:

@timestamp=DATEDIFF(second,{d '1970-01-01'},@datetime) 

Where @datetime is the date and time value you want to convert. The designation {d 'yyyy-mm-dd} is an ODBC escape sequence.

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 now as @Ousman below:

 SELECT UNIX_TIMESTAMP(GETDATE()); 
+26
source

Source: https://habr.com/ru/post/1239147/


All Articles