Skip to content
Advertisement

SQL date conversion to UNIX time stamp gives multiple UNIX times for same time stamp

When I attempt to convert UNIX timestamp to a timestamp recognized by SQL I get multiple UNIX timestamps.

For example the image shows that the following code will provide two different date/times i.e 05/09/2019 00:00:00.00 and 19/03/2019 00:00:00.000 for the same UNIX time of 1567641600

 DATEADD(s, localmarketanal.timeslot, '19700101') AS mytimeslot

enter image description here

Advertisement

Answer

CREATE FUNCTION dbo.fn_ConvertToDateTime (@Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
    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

Ref: How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement