SQL Server: Convert Between UTC and Local Time Precisely

早过忘川 提交于 2019-11-30 21:29:05

I could not find any way at all doing this using T-SQL alone. I solved it using SQL CLR:

public static class DateTimeFunctions
{
    [SqlFunction(IsDeterministic = true, IsPrecise = true)]
    public static DateTime? ToLocalTime(DateTime? dateTime)
    {
        if (dateTime == null) return null;
        return dateTime.Value.ToLocalTime();
    }

    [SqlFunction(IsDeterministic = true, IsPrecise = true)]
    public static DateTime? ToUniversalTime(DateTime? dateTime)
    {
        if (dateTime == null) return null;
        return dateTime.Value.ToUniversalTime();
    }
}

And the following registration script:

CREATE FUNCTION ToLocalTime(@dateTime DATETIME2) RETURNS DATETIME2 AS EXTERNAL NAME AssemblyName.[AssemblyName.DateTimeFunctions].ToLocalTime; 
GO
CREATE FUNCTION ToUniversalTime(@dateTime DATETIME2) RETURNS DATETIME2 AS EXTERNAL NAME AssemblyName.[AssemblyName.DateTimeFunctions].ToUniversalTime; 

It is a shame to be forced to go to such effort to convert to and from UTC time.

Note, that these functions interpret local time as whatever is local to the server. It is recommended to have clients and servers set to the same time zone to avoid any confusion.

    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'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!