SQL Server - Convert date field to UTC

前端 未结 12 687
故里飘歌
故里飘歌 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 14:05

    As mentioned here previously, there is no build-in way to perform time zone rules aware date conversion in SQL Server (at least as of SQL Server 2012).

    You have essentially three choices to do this right:

    1. Perform the conversion outside of SQL Server and store results in the database
    2. Introduce time zone offset rules in a standalone table and create stored procedures or UDFs to reference the rules table to perform conversions. You can find one take on this approach over at SQL Server Central (registration required)
    3. You can create a SQL CLR UDF; I will describe the approach here

    While SQL Server does not offer tools to perform time zone rules aware date conversion, the .NET framework does, and as long as you can use SQL CLR, you can take advantage of that.

    In Visual Studio 2012, make sure you have the data tools installed (otherwise, SQL Server project won't show up as an option), and create a new SQL Server project.

    Then, add a new SQL CLR C# User Defined Function, call it "ConvertToUtc". VS will generate boiler plate for you that should look something like this:

    public partial class UserDefinedFunctions
    {
        [Microsoft.SqlServer.Server.SqlFunction]
        public static SqlString ConvertToUtc()
        {
            // Put your code here
            return new SqlString (string.Empty);
        }
    }
    

    We want to make several changes here. For one, we want to return a SqlDateTime rather than a SqlString. Secondly, we want to do something useful. :)

    Your revised code should look like this:

    public partial class UserDefinedFunctions
    {
        [Microsoft.SqlServer.Server.SqlFunction]
        public static SqlDateTime ConvertToUtc(SqlDateTime sqlLocalDate)
        {
            // convert to UTC and use explicit conversion
            // to return a SqlDateTime
            return TimeZone.CurrentTimeZone.ToUniversalTime(sqlLocalDate.Value);
        }
    }
    

    At this point, we are ready to try it out. The simplest way is to use the built-in Publish facility in Visual Studio. Right-click on the database project and select "Publish". Set up your database connection and name, and then either click "Publish" to push the code into the database or click "Generate Script" if you'd like to store the script for posterity (or to push the bits into production).

    Once you have the UDF in the database, you can see it in action:

    declare @dt as datetime
    set @dt = '12/1/2013 1:00 pm'
    select dbo.ConvertToUtc(@dt)
    

提交回复
热议问题