Recently I needed to migrate data from one source to different instances of databases that will be used in different countries (time zones). I expected to see a predefined SQL function that gets the datetime value along with the Time zone and returns the datetime in UTC format, but could not find such a function which was kind ofsurprising to me!
Based on my research, it can be achieved using a CLR function. Let's follow the steps below:
Step 1: We need to create the assembly CLR function which does the conversion. The CLR function can be written in .net and gives us the assembly (dll file) to be used in SQL Server. If you are not sure how to create a CLR function, refer to the link below:
Step 2: When the dll file is created, we can create an assembly to call it. For example, we name the dll file ‘TzConverter’ and copied it to the folder below:
'C:\Users\Dev\UTC\TzConverter.dll'
In creating the assembly to call CLR function, it is important to set the TRUSTWORTHY ON and create the assembly with UNSAFE permission set: USE testDB
GO
ALTER DATABASE testDB
SET TRUSTWORTHY ON;
GO
CREATE ASSEMBLY tzconverter
FROM 'C:\Users\Dev\UTC\TzConverter.dll'
WITH PERMISSION_SET = UNSAFE
GO
Step 3: Now that the assembly has been created, we need to create the SQL function. It enables us to call the CLR function in SQL Server:
CREATE FUNCTION [dbo].[ToUtc](@dt [datetime], @timeZone NVARCHAR(100))
RETURNS [datetime] WITH EXECUTEAS CALLER AS
EXTERNAL NAME tzconverter.[UserDefinedFunctions].ToUtc
GO
sp_configure'clr enabled', 1;
GO
RECONFIGURE;
GO
Ok, we are done. Call the function and get the UTC datetime!
--- Examples : It shows the current date time in AustralianEastern standard time format SELECT GETDATE(), [dbo].ToUtc(GetDate(), 'AUS Eastern Standard Time')
--- Examples : It shows the current date time in New Zealandstandard time format
SELECT GETDATE(), [dbo].ToUtc(GetDate(), 'New Zealand Standard Time')