SQL Server:准确地在UTC和本地时间之间进行转换

use*_*824 5 t-sql database sql-server datetime utc

我在SQL Server 2008 R2数据库中有几列需要从本地时间(sql server所在的时区)转换为UTC.

我在StackOverflow上看到了很多类似的问题,但是答案都无法正常使用夏令时,他们只考虑当前的差异并抵消了日期.

usr*_*usr 7

我单独使用T-SQL无法找到任何方法.我用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下注册脚本:

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; 
Run Code Online (Sandbox Code Playgroud)

被迫转换到UTC时间的努力是一种耻辱.

请注意,这些函数将本地时间解释为服务器的本地时间.建议将客户端和服务器设置为相同的时区,以避免混淆.