Epoch and Date Time Conversion in Microsoft SQL Server

Microsoft SQL Server is a popular relational database management system. It is widely used for storing and retrieving data. It is feature rich database system with many date time functions like CURRENT_TIMESTAMP(), GETDATE(), DATEADD() etc. to play with date time.

Here we will explain SQL Server date time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in SQL Server

We can use CURRENT_TIMESTAMP() function to get the current unix timestamp.

CURRENT_TIMESTAMP()

Output: 1624705077

Convert epoch or Unix timestamp to date in SQL Server

We can use the DATEADD() function to convert the epoch or timestamp to readable date format.

DATEADD(s, 1624705077, '1970-01-01 00:00:00')

Output: 2021-06-26 22:50:27.000

Convert date to epoch or unix timestamp in SQL Server

we can convert the date time string to unix timestamp using UNIX_TIMESTAMP() and STR_TO_DATE() function like below:

DATEDIFF(s, '1970-01-01 00:00:00', '2021-06-26 22:50:27.000')

Output: 1624705077


More about date time in SQL Server