Link to home
Start Free TrialLog in
Avatar of dbaSQL
dbaSQLFlag for United States of America

asked on

BIGINT to DATETIME to GMT, or just BIGINT to GMT

@Time is BIGINT.  I need to convert to DATETIME2, but GMT.  I am in CST.

SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
Returns:  1368617884
(i tried DATEDIFF(mcs, because we need microseconds format on the BIGINT, but it failed with overflow, saying it was too large.)


DECLARE @Time BIGINT = 1368617884
SELECT dbo.fn_bigintDatetime (@Time)

Result:  1970-01-16 20:10:18.0000000

Of course, my date should be 2013-05-15.....

Does anyone see my error?



CREATE FUNCTION [dbo].[fn_bigintDateTime]
(@Timestamp bigint)
RETURNS datetime2
AS
BEGIN
       DECLARE @GMTDatetime datetime2
       select @GMTDatetime =
       CASE
       WHEN dateadd(ss, @Timestamp/1000, '1970-01-01')
       BETWEEN
           Convert(DATETIME, Convert(VARCHAR(4), Year(dateadd(ss, @Timestamp/1000, '1970-01-01') )) + '-03-' + Convert(VARCHAR(2), (31 - (5 * Year(dateadd(ss, @Timestamp/1000, '1970-01-01') )/4 + 4) % 7)) + ' 01:00:00', 20)
       AND
           Convert(DATETIME, Convert(VARCHAR(4), Year(dateadd(ss, @Timestamp/1000, '1970-01-01') )) + '-10-' + Convert(VARCHAR(2), (31 - (5 * Year(dateadd(ss, @Timestamp/1000, '1970-01-01') )/4 + 1) % 7)) + ' 02:00:00', 20)
       THEN Dateadd(hh, 1, dateadd(ss, @Timestamp/1000, '1970-01-01'))
       ELSE Dateadd(hh, 0, dateadd(ss, @Timestamp/1000, '1970-01-01'))
       END
RETURN @GMTDatetime    
END
GO
SOLUTION
Avatar of Lee
Lee
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If that is CST and you want GMT, then something like this::
SELECT CAST(DATEADD(minute, DATEDIFF(minute, GETUTCDATE(), GETDATE()), DATEADD(SECOND, 1368617884, '19700101')) AS datetime2)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Too true.  You are absolutely right.
Avatar of dbaSQL

ASKER

sorry, guys.  insanity.  i will be back soon.
Avatar of dbaSQL

ASKER

You're not missing anything, ac.  i was overthinking it.
this works fine:  DATEADD(s,(@Time/1000),'1/1/1970')

Very good point, matthewspatrick .  And that is definitely something i am going to have to be wary of.