How can I convert bigint (UNIX timestamp) to datetime in SQL Server?
This worked for me:
Select dateadd(S, [unixtime], '1970-01-01')From [Table]
In case any one wonders why 1970-01-01, This is called Epoch time.
Below is a quote from Wikipedia:
The number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970,[1][note 1] not counting leap seconds.
try:
CREATE FUNCTION dbo.fn_ConvertToDateTime (@Datetime BIGINT)RETURNS DATETIMEASBEGIN DECLARE @LocalTimeOffset BIGINT ,@AdjustedLocalDatetime BIGINT; SET @LocalTimeOffset = DATEDIFF(second,GETDATE(),GETUTCDATE()) SET @AdjustedLocalDatetime = @Datetime - @LocalTimeOffset RETURN (SELECT DATEADD(second,@AdjustedLocalDatetime, CAST('1970-01-01 00:00:00' AS datetime)))END;GO
If anyone getting below error:
Arithmetic overflow error converting expression to data type int
due to unix timestamp is in bigint (instead of int), you can use this:
SELECT DATEADD(S, CONVERT(int,LEFT(1462924862735870900, 10)), '1970-01-01')FROM TABLE
Replace the hardcoded timestamp for your actual column with unix-timestamp
Source: MSSQL bigint Unix Timestamp to Datetime with milliseconds