Technical Article

Convert a given date to GMT

,

In SQL 7 you had no way to convert local time to GMT (UTC time) which was added in SQL 2K as GETUTCDATE() which will output the current date you would get with GETDATE() but a it's GMT counterpart. Although this was a great improvement I work with data on another server that's front end application stores dates as number of seconds since 1/1/1970 GMT. As this is one of the major indexes I really wanted to take advantage of this to pull the data. I also wanted to right this once and be able to reuse over and over. So I wrote a stored procedure to make the conversion from the user input data passed from another procedure accessed from my front end apps. The stored procedure can take any inserted date and convert it to the proper GMT date for that time by taking into account the time of year (the only exception is 1AM to 2AM the last Sunday in October when we fall back and thus it could be either or and I did not put a bit in as my needs did not warrant. This can be easily modified to do so or return the number of seconds instead of date format by making the adjust where each is noted.

CREATE PROCEDURE iP_GMTConvrt

@DateIn VARCHAR(20),
@DateOut VARCHAR(50)OUTPUT

AS

--This Code Converts Local Time to GMT
Declare @DateUse VARCHAR(20)
Declare @TimeChg VARCHAR(20)
Declare @DayVal NUMERIC
Declare @GMT VARCHAR(20)

SET @DateUse = @DateIn --Get Current DateTime

If Month(@DateUse) >= 10 --Check To See if Date is Oct, Nov, or Dec
BEGIN
Set @TimeChg = '10/31/' + Cast(Year(@DateUse) as varchar) --Use Oct 31 as strt Point
END
ELSE
Set @TimeChg = '4/1/' + Cast(Year(@DateUse) as varchar) --Use April 1 as start point

Set @DayVal = DatePart(weekday,@TimeChg) --Is the Start Point a Sunday

If @DayVal <> 1 --If Not then when is the proper Time Change Sunday
If DatePart(m,@TimeChg) = 4 --Is the base the April Value
Begin
Set @TimeChg = DateAdd(d,8 - @DayVal,@TimeChg) --For April it is the first Sunday of the Month
End
Else
Set @TimeChg = DateAdd(d,-@DayVal + 1,@TimeChg) --For Oct it is the last Sunday of the Month

Set @TimeChg = DateAdd(hh,2,@TimeChg) --Alaways Happens at 2 am

If DatePart(m,@TimeChg) = 4 --If Time Change is Based on April
Begin
If @DateUse < @TimeChg --If DateUse < The Time Change Date & Time
Begin
Set @DateUse = DateAdd(hh,5,@DateUse) --GMT 5 hours ahead
End
Else
Set @DateUse = DateAdd(hh,4,@DateUse) --GMT 4 hours ahead
End
Else
If @DateUse < @TimeChg --If DateUse < The Time Change Date & Time
Begin
Set @DateUse = DateAdd(hh,4,@DateUse) --GMT 4 hours ahead
End
Else
Set @DateUse = DateAdd(hh,5,@DateUse) --GMT 5 hours ahead


--Set @GMT = DateDiff(s,'01/01/1970',@DateUse) --How many seconds since 1/1/1970 GMT to @DateUse GMT
Set @GMT = @DateUse -- Return in date format
--End GMT Code

Set @DateOut = @GMT

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating