SQL Server - Convert date field to UTC

前端 未结 12 752
故里飘歌
故里飘歌 2020-12-23 13:39

I have recently updated my system to record date/times as UTC as previously they were storing as local time.

I now need to convert all the local stored date/times to

12条回答
  •  没有蜡笔的小新
    2020-12-23 13:40

    We can convert ServerZone DateTime to UTC and UTC to ServerZone DateTime

    Simply run the following scripts to understand the conversion then modify as what you need

    --Get Server's TimeZone
    DECLARE @ServerTimeZone VARCHAR(50)
    EXEC MASTER.dbo.xp_regread 'HKEY_LOCAL_MACHINE',
    'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
    'TimeZoneKeyName',@ServerTimeZone OUT
    
    -- ServerZone to UTC DATETIME
    DECLARE @CurrentServerZoneDateTime DATETIME = GETDATE()
    DECLARE @UTCDateTime  DATETIME =  @CurrentServerZoneDateTime AT TIME ZONE @ServerTimeZone AT TIME ZONE 'UTC' 
    --(OR)
    --DECLARE @UTCDateTime  DATETIME = GETUTCDATE()
    SELECT @CurrentServerZoneDateTime AS CURRENTZONEDATE,@UTCDateTime AS UTCDATE
    
    -- UTC to ServerZone DATETIME
    SET @CurrentServerZoneDateTime = @UTCDateTime AT TIME ZONE 'UTC' AT TIME ZONE @ServerTimeZone
    SELECT @UTCDateTime AS UTCDATE,@CurrentServerZoneDateTime AS CURRENTZONEDATE
    

    Note: This(AT TIME ZONE) working on only SQL Server 2016+ and this advantage is automatically considering Daylight while converting to particular Time zone

提交回复
热议问题