Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIX_TIMESTAMP in SQL Server

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

Thanks in advance !

like image 611
TheZver Avatar asked Jan 12 '12 15:01

TheZver


People also ask

What is Unix_timestamp SQL?

UNIX_TIMESTAMP() :This function in MySQL helps to return a Unix timestamp. We can define a Unix timestamp as the number of seconds that have passed since '1970-01-01 00:00:00'UTC. Even if you pass the current date/time or another specified date/time, the function will return a Unix timestamp based on that.

How do I convert Unix time to normal time in SQL?

Oracle Database Here, we use Oracle's TO_DATE() function to construct a date of 1970-01-01. We then add our Unix timestamp to that date to get our result. In this case, we use NUMTODSINTERVAL() to convert the Unix timestamp into an interval value. The result is a DATE value.


1 Answers

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) 
like image 188
Dunc Avatar answered Sep 17 '22 17:09

Dunc