SQL Server: Convert Between UTC and Local Time Precisely

后端 未结 2 1970
鱼传尺愫
鱼传尺愫 2021-01-06 02:09

I have a few columns in an SQL server 2008 R2 database that i need to convert from local time (the time zone the sql server is in) to UTC.

I have seen quite a few si

2条回答
  •  日久生厌
    2021-01-06 02:55

        DECLARE @convertedUTC datetime, @convertedLocal datetime
        SELECT DATEADD(
                        HOUR,                                    -- Add a number of hours equal to
                        DateDiff(HOUR, GETDATE(), GETUTCDATE()), -- the difference of UTC-MyTime
                        GetDate()                                -- to MyTime
                        )
    
        SELECT @convertedUTC = DATEADD(HOUR,DateDiff(HOUR, GETDATE(), GETUTCDATE()),GetDate()) --Assign the above to a var
    
        SELECT DATEADD(
                        HOUR,                                    -- Add a number of hours equal to
                        DateDiff(HOUR, GETUTCDATE(),GETDATE()), -- the difference of MyTime-UTC
                        @convertedUTC                           -- to MyTime
                        )
    
        SELECT @convertedLocal = DATEADD(HOUR,DateDiff(HOUR, GETUTCDATE(),GETDATE()),GetDate()) --Assign the above to a var
    
    
        /* Do our converted dates match the real dates? */
        DECLARE @realUTC datetime = (SELECT GETUTCDATE())
        DECLARE @realLocal datetime = (SELECT GetDate())
    
        SELECT 'REAL:', @realUTC AS 'UTC', @realLocal AS 'Local'
        UNION
        SELECT 'CONVERTED:', @convertedUTC AS 'UTC', @convertedLocal AS 'Local'
    

提交回复
热议问题