Frequently we get requirements for UTC times in Azure SQL databases to be converted into various world time zones. Whilst scripting within the table builds and adding columns, or relying on sever settings, can produce this outcome there is a more flexible approach using the AT TIME ZONE (T-SQL) statement. Changes in Time Zone are automatically catered for throughout the year, dependent upon the date.
Using that command within statements provides a simple set of results that can written into queries as below. In this instance it is UTC converted to cater for Daylight Saving in the UK
This will produce results that provide the additional column, however additional columns add to storage and table sizes. We therefore took the approach of creating a SQL function that can be utilised in any query or view to create a more agile use of the command.
Creating a function as the script below
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE FUNCTION [dbo].[TimeZoneUK] (@UTCDate AS DATETIMEOFFSET(3))
Description: Add UK Time Zone and Daylight Savings to UTC Datetime
RETURN @UTCDate AT TIME ZONE 'UTC' AT TIME ZONE 'GMT Standard Time'
Enabling us to utilise that function in SQL scripts and views without the need to repeat the AT TIME ZONE commands on each line by placing the function in from of the UTC DateTime column already in the database as below.
CONVERT(INT,CONVERT(CHAR(10),(CAST(dbo.TimeZoneUK(TimestampCreated) as date)), 112) ) as [Date Key]
,DATEPART(HOUR,dbo.TimeZoneUK(TimestampCreated)) AS [Hour Key]
,CAST(dbo.TimeZoneUK(TimestampCreated) AS DATE) AS [Event Date]
With the results converted to UK DST within the appropriate dates.
Further details on the AT TIME ZONE command can be found within Microsoft's documentation here.