Technical Article

UDF_GetGMTOffset

,

Here is an example query that illustrates how to use the function to easily convert to and from UTC/GMT time and the SQL Server's local time.

SELECT GETDATE() AS 'Local Time',
GETUTCDATE() AS 'GMT Time',
DATEADD(HOUR, dbo.UDF_GetGMTOffset(), GETUTCDATE()) AS 'GMT Time to Local Time',
DATEADD(HOUR, dbo.UDF_GetGMTOffset() * -1, GETDATE()) AS 'Local Time to GMT Time',
dbo.UDF_GetGMTOffset() AS 'GMT Offset'
Results
Local TimeGMT TimeGMT Time to Local TimeLocal Time to GMT TimeGMT Offset
2010-11-04 09:45:55.8272010-11-04 14:45:55.8272010-11-04 09:45:55.8272010-11-04 14:45:55.827-5
/*
============================================================================================
            Name: UDF_GetGMTOffset
Parameter(s): (none)
       Returns: (value) = The GMT offset of the SQL Server's local time.
 Description: Calculates the offset between the UTC time and the SQL Server's local time.

                     Note: This function accounts for Daylight Savings Time only if configured
                    correctly in the Windows date and time settings of the SQL Server.
============================================================================================
*/CREATE FUNCTION [dbo].[UDF_GetGMTOffset]()
RETURNS int
AS
BEGIN
    DECLARE @GMTOffset int;
    -- Calculate the difference between the UTC time and the SQL Server's time
    SET @GMTOffset = (SELECT DATEDIFF(hh,GETUTCDATE(),GETDATE()));
    RETURN @GMTOffset;
END
GO

Rate

1.6 (5)

You rated this post out of 5. Change rating

Share

Share

Rate

1.6 (5)

You rated this post out of 5. Change rating