Click here to Skip to main content
15,867,967 members
Articles / Database Development / SQL Server
Article

SQL 2005 Time Zone Conversion Functions

Rate me:
Please Sign up or sign in to vote.
4.89/5 (7 votes)
30 Nov 2008CPOL7 min read 173.5K   2.5K   49   51
How to create simple SQL time zone functions to use in queries.

Image 1

Introduction

I work for a rather large company that spans countries and time zones, with multiple data centers in multiple locations. While working on a project where data was coming from different locations into a common data repository, we ran into a situation. Our application developers had not setup the application to convert date-time values into a common time zone; each application used the local time of the servers that hosted the application. In engaging the vendor, it was soon discovered that it was cost prohibitive to re-write the application to do so. One of the design aspects of the application architecture included MS SQL Server 2005 as the back-end database software. I did a lot of research on Microsoft's website, and the only time zone conversion functions that I could find were relative to analysis services, and would not provide me with a solution to my problem. So, my options were to pay someone to modify our application, or create a process in the database environment to perform the conversions as data is inserted into the common database environment.

Using the Code

A few years ago, we were primarily an Oracle database shop. Oracle natively comes with some time zone conversion functions. My approach to resolve this issue was to setup an environment in MS SQL Server 2005 similar to the environment that I was used to in Oracle (a scalar function called NEW_TIME that took three parameters; date to convert, original time zone value, conversion time zone, and the function returns the converted value). The only thing about the Oracle date time conversion functions that I did not like was that you have to know whether you want to use the standard or the daylight code for the same time zone (e.g., CST vs. CDT). I think that it would be better for the functions to be able to determine whether the date should be converted using the daylight or standard offset.

First, I created a TIME_ZONES table to store the time zone conversion parameters (see the table structure below).

SQL
CREATE TABLE [dbo].[TIME_ZONES] (
    [TIMEZONE_CD] [varchar] (6) NOT NULL ,
    [TIMEZONE_NAME] [varchar] (60) NOT NULL ,
    [OFFSET_HR] [int] NOT NULL ,
    [OFFSET_MI] [int] NOT NULL ,
    [DST_OFFSET_HR] [int] NOT NULL ,
    [DST_OFFSET_MI] [int] NOT NULL ,
    [DST_EFF_DT] [varchar] (10) NOT NULL ,
    [DST_END_DT] [varchar] (10) NOT NULL ,
    [EFF_DT] DATETIME NOT NULL,
    [END_DT] DATETIME NOT NULL
)

The main challenge that I had in putting together this table was to determine how to come up with a way to use a generic code for the daylight start and end dates that would be applicable for any year, so that I did not have to maintain a table of actual dates and times that show when day light savings starts or ends for each time zone. So, I came up with a code that I could convert date time values to in order to determine if that date falls within day light or standard time. The code is formatted as follows; MMWDHHmm. MM = two digit month (e.g., March = 03), W = the week of the month (e.g., the second week of the month = 2), D = the day of the week, Sunday is the start of the week which starts at 1 (e.g., Monday = 2), HH = two digit hour, 24 hour time (e.g., 2:00 am = 02, and 2:00 pm = 14), mm = two digit minute (e.g., 35 minutes after the hour is 35). Example: On Sunday, on the second week of the month, for the month of March, at 2:00 am, would be: 03210200.

An example of one of the records is as follows: TIMEZONE_CD = 'CT', TIMEZONE_NAME = 'CENTRAL TIME', OFFSET_HR = -6, OFFSET_MI = 0, DST_OFFSET_HR = -5, DST_OFFSET_MI = 0, DST_EFF_DT = 03210200, DST_END_DT = '11110200' , EFF_DT = '11/30/2008', END_DT = '12/31/9999'.

After the table was created and populated, I started on the creation of the functions. I started with the function to convert a provided date-time to Universal (UTC) or Greenwich time (GMT). The function that I setup takes two parameters; the date-time to convert, and the time zone code. The function declares some variables, and then populates them with the values from the TIME_ZONES table using the provided time zone code. It then checks to see if the date-time provided was within the daylight effective and end dates, so that it would know which offset to adjust the provided date time with, and lastly, it returns the adjusted date-time in UTC time.

SQL
CREATE FUNCTION GET_UTCTIME 
    (@DT AS DATETIME, 
     @TZ AS VARCHAR(12))
RETURNS DATETIME
AS
BEGIN
-- DECLARE VARIABLES
    DECLARE @NEWDT AS DATETIME
    DECLARE @OFFSETHR AS INT
    DECLARE @OFFSETMI AS INT
    DECLARE @DSTOFFSETHR AS INT
    DECLARE @DSTOFFSETMI AS INT
    DECLARE @DSTDT AS VARCHAR(10)
    DECLARE @DSTEFFDT AS VARCHAR(10)
    DECLARE @DSTENDDT AS VARCHAR(10)
    
-- GET THE DST parameter from the provided datetime
    -- This gets the month of the datetime provided (2 char value)
    SELECT @DSTDT = CASE LEN(DATEPART(month, @DT)) 
                WHEN 1 
                    then '0' + CONVERT(VARCHAR(2),DATEPART(month, @DT)) 
                ELSE CONVERT(VARCHAR(2),DATEPART(month, @DT)) END
    -- This gets the occurrence of the day of the week within the month 
      -- (i.e. first Sunday, or second Sunday...) (1 char value)
    SELECT @DSTDT = @DSTDT + CONVERT(VARCHAR(1),(DATEPART(day,@DT) + 6) / 7)
    -- This gets the day of the week for the provided datetime (1 char value)
    SELECT @DSTDT = @DSTDT + CONVERT(VARCHAR(1),DATEPART(dw, @DT))
    -- This gets the hour for the provided datetime (2 char value)
    SELECT @DSTDT = @DSTDT + CASE LEN(DATEPART(hh, @DT)) 
                    WHEN 1 
                        then '0' + CONVERT(VARCHAR(2),DATEPART(hh, @DT)) 
                    ELSE CONVERT(VARCHAR(2),DATEPART(hh, @DT)) END
    -- This gets the minutes for the provided datetime (2 char value)
    SELECT @DSTDT = @DSTDT + CASE LEN(DATEPART(mi, @DT)) 
                    WHEN 1 
                        then '0' + CONVERT(VARCHAR(2),DATEPART(mi, @DT)) 
                    ELSE CONVERT(VARCHAR(2),DATEPART(mi, @DT)) END
    
    -- This query gets the timezone information
    -- from the TIME_ZONES table for the provided timezone
    SELECT
        @OFFSETHR=offset_hr,
        @OFFSETMI=offset_mi,
        @DSTOFFSETHR=dst_offset_hr,
        @DSTOFFSETMI=dst_offset_mi,
        @DSTEFFDT=dst_eff_dt,
        @DSTENDDT=dst_END_dt
    FROM time_zones
    WHERE timezone_cd = @TZ AND
        @DT BETWEEN eff_dt AND end_dt
    
    -- Checks to see if the DST parameter
    -- for the datetime provided is within the DST 
    -- parameter for the timezone
    IF @DSTDT BETWEEN @DSTEFFDT AND @DSTENDDT
    BEGIN
        -- Increase the datetime by the hours
        -- and minutes assigned to the timezone
        SET @NEWDT = DATEADD(hh,ABS(@DSTOFFSETHR),@DT)
        SET @NEWDT = DATEADD(mi,ABS(@DSTOFFSETMI),@NEWDT)
    END
    -- If the DST parameter for the provided datetime is not within the defined
    -- DST eff and end dates for the timezone then use the standard time offset
    ELSE
    BEGIN
        -- Increase the datetime by the hours
        -- and minutes assigned to the timezone
        SET @NEWDT = DATEADD(hh,ABS(@OFFSETHR),@DT)
        SET @NEWDT = DATEADD(mi,ABS(@OFFSETMI),@NEWDT)
    END

    -- Return the new date that has been converted to UTC time
    RETURN @NEWDT
END

The next function that I needed to create was one that would convert time from UTC time to a specified time zone, similar to the GET_UTCTIME function. This one takes two parameters; the date-time to be converted and the time zone code to convert the provided date-time to. The function declares some variables, then it converts the provided date-time to the DST parameter format (MMWDHHmm). Next, it uses the provided time zone code to get the parameters from the TIME_ZONES table, and populates the variables with the returned values. Last, it checks to see if the provided date-time falls within the daylight range, and then applies the proper offset value, and then returns the adjusted date-time value.

SQL
CREATE FUNCTION GET_TZTIME 
    (@DT AS DATETIME, 
     @TZ AS VARCHAR(12))
RETURNS DATETIME
AS
BEGIN
-- DECLARE VARIABLES
    DECLARE @NEWDT AS DATETIME
    DECLARE @OFFSETHR AS INT
    DECLARE @OFFSETMI AS INT
    DECLARE @DSTOFFSETHR AS INT
    DECLARE @DSTOFFSETMI AS INT
    DECLARE @DSTDT AS VARCHAR(10)
    DECLARE @DSTEFFDT AS VARCHAR(10)
    DECLARE @DSTENDDT AS VARCHAR(10)
    
-- GET THE DST parameter from the provided datetime
    -- This gets the month of the datetime provided (2 char value)
    SELECT @DSTDT = CASE LEN(DATEPART(month, @DT)) 
                WHEN 1 
                    then '0' + CONVERT(VARCHAR(2),DATEPART(month, @DT)) 
                ELSE CONVERT(VARCHAR(2),DATEPART(month, @DT)) END
    -- This gets the occurrence of the day of the week within the month
    --(i.e. first Sunday, or second Sunday...) (1 char value)
    SELECT @DSTDT = @DSTDT + CONVERT(VARCHAR(1),(DATEPART(day,@DT) + 6) / 7)
    -- This gets the day of the week for the provided datetime (1 char value)
    SELECT @DSTDT = @DSTDT + CONVERT(VARCHAR(1),DATEPART(dw, @DT))
    -- This gets the hour for the provided datetime (2 char value)
    SELECT @DSTDT = @DSTDT + CASE LEN(DATEPART(hh, @DT)) 
                    WHEN 1 
                        then '0' + CONVERT(VARCHAR(2),DATEPART(hh, @DT)) 
                    ELSE CONVERT(VARCHAR(2),DATEPART(hh, @DT)) END
    -- This gets the minutes for the provided datetime (2 char value)
    SELECT @DSTDT = @DSTDT + CASE LEN(DATEPART(mi, @DT)) 
                    WHEN 1 
                        THEN '0' + CONVERT(VARCHAR(2),DATEPART(mi, @DT)) 
                        ELSE CONVERT(VARCHAR(2),DATEPART(mi, @DT)) END
    
    -- This query gets the timezone information from the TIME_ZONES table
    -- for the provided timezone
    SELECT
        @OFFSETHR=offset_hr,
        @OFFSETMI=offset_mi,
        @DSTOFFSETHR=dst_offset_hr,
        @DSTOFFSETMI=dst_offset_mi,
        @DSTEFFDT=dst_eff_dt,
        @DSTENDDT=dst_END_dt
    FROM time_zones
    WHERE timezone_cd = @TZ AND
        @DT BETWEEN eff_dt AND end_dt
    
    -- Checks to see if the DST parameter for the datetime provided
    -- is within the DST parameter for the timezone
    IF @DSTDT BETWEEN @DSTEFFDT AND @DSTENDDT
    BEGIN
        -- Increase the datetime by the hours and minutes assigned to the timezone
        SET @NEWDT = DATEADD(hh,@DSTOFFSETHR,@DT)
        SET @NEWDT = DATEADD(mi,@DSTOFFSETMI,@NEWDT)
    END
    -- If the DST parameter for the provided datetime is not within the defined
    -- DST eff and end dates for the timezone then use the standard time offset
    ELSE
    BEGIN
        -- Increase the datetime by the hours and minutes assigned to the timezone
        SET @NEWDT = DATEADD(hh,@OFFSETHR,@DT)
        SET @NEWDT = DATEADD(mi,@OFFSETMI,@NEWDT)
    END

    -- Return the new date that has been converted from UTC time
    RETURN @NEWDT
END

Now that I have the two functions to convert time to and from UTC, I can now create the main function that I will use for most queries, NEW_TIME. This function will use the previous two functions to deliver the desired results. This function takes three parameters: the date-time to be converted, the time zone code of the provided date-time, and the time zone to convert the provided date-time to. The function starts by checking to see if the initial time zone code is either UTC or GMT. The reason for this is that if the starting point is one of those, then the function will not need to convert it to UTC time. If the initial time zone is not GMT or UTC, then the provided date time is converted to UTC time using the provided initial time zone code, and that value is applied to the @NEWDT variable. If the code is UTC or GMT, then the @NEWDT variable is set to the provided date-time. Next, the function converts the value in the @NEWDT variable using the GET_TZTIME function and the second time zone code provided, and returns the converted value.

SQL
CREATE FUNCTION NEW_TIME
    (@DT AS DATETIME, 
     @TZ1 AS VARCHAR(12),
     @TZ2 AS VARCHAR(12))
RETURNS DATETIME
AS
BEGIN
    -- Declare variables
    DECLARE @NEWDT AS DATETIME
    
    -- Check to see if the provided timezone
    -- for the source datetime is in GMT or UTC time
    -- If it is not then convert the provided datetime to UTC time
    IF NOT @TZ1 IN ('GMT','UTC')
    BEGIN
        SELECT @NEWDT = dbo.GET_UTCTIME(@DT,@TZ1)
    END
    ELSE
    -- If the provided datetime is in UTC or GMT time
    -- then set the NEWTIME variable to this value
    BEGIN
        SET @NEWDT = @DT
    END

    -- Check to see if the provided conversion timezone is GMT or UTC
    -- If it is then no conversion is needed.
    -- If it is not then convert the provided datetime to the desired timezone
    IF NOT @TZ2 IN ('GMT','UTC')
    BEGIN
        SELECT @NEWDT = dbo.GET_TZTIME(@NEWDT,@TZ2)
    END

    -- Return the new converted datetime
    RETURN @NEWDT
    
END

Final Solution Architecture

The final solution looks like this. We have our local applications with their data stores. We setup database replication so that shortly after the record has been written to the local database, it is replicated to the central data store. The central data store tables have triggers on them that convert the local date-time to UTC time. The records have a field that stores the original local date-time, and another field to store the converted UTC date-time. All of our reports use the UTC time, and the time zone functions to convert the date-time to the desired time zone of the report user.

So far, I have not run into any issues with this setup to require any changes, though I am sure it is not perfect and could use some adjustments here and there. For the application that this was specifically designed for, it has worked out really well.

Points of Interest

The one annoying thing that I have not had a chance to research about is that in order to use the functions, you are required to use the schema owner name prior to the function name (e.g., dbo.NEW_TIME()). I am sure that there is a way around this, but I have not come across it yet, and it can be annoying at times to remember to always use that, since I did not have to when working with Oracle previously, or with other database objects within the MS SQL Server 2005 environment.

Revision History

  • 11-17-2008
    • Original article.
  • 11-30-2008: Based upon a query from user stribbed, I made some modifications to this article - Thanks for the feedback!
    • Added effective and end date fields to the TIME_ZONES table.
    • Modified GET_TZTIME so it only looks for the time zone config that is within the effective and end dates in the TIME_ZONES table.
    • Modified GET_UTCTIME so it only looks for the time zone config that is within the effective and end dates in the TIME_ZONES table.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Other
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
kumaranand5610-May-17 3:37
kumaranand5610-May-17 3:37 
QuestionPrecisely the workaround for MS SQL 2005 I needed Pin
eddiemjm432125-Sep-14 23:39
eddiemjm432125-Sep-14 23:39 
SuggestionA new alternative solution for such issues: T-SQL Toolbox on CodePlex Pin
adss20093-May-14 0:53
adss20093-May-14 0:53 
QuestionProblem with Time Zone calculation for this year Pin
Mark Kilroy11-Mar-14 12:02
Mark Kilroy11-Mar-14 12:02 
QuestionTimezones info for Europe Pin
Maikel_D9-Apr-13 21:31
Maikel_D9-Apr-13 21:31 
QuestionExcellent Pin
Patel,N25-Jan-13 10:11
Patel,N25-Jan-13 10:11 
QuestionWhich is better? Pin
AndyTexas15-Nov-10 5:54
AndyTexas15-Nov-10 5:54 
AnswerRe: Which is better? Pin
robertford16-Nov-10 14:19
robertford16-Nov-10 14:19 
GeneralRe: Which is better? Pin
shell_l_d6-Feb-12 17:30
shell_l_d6-Feb-12 17:30 
GeneralSuggested updates Pin
Colin 215-Apr-10 1:17
Colin 215-Apr-10 1:17 
QuestionRe: Suggested updates [modified] Pin
shell_l_d20-Jul-10 16:13
shell_l_d20-Jul-10 16:13 
AnswerRe: Suggested updates Pin
robertford21-Jul-10 3:22
robertford21-Jul-10 3:22 
GeneralUsing the function in very large data sets Pin
robertford11-Jun-09 18:27
robertford11-Jun-09 18:27 
GeneralCode Change Pin
robertford11-Jun-09 18:04
robertford11-Jun-09 18:04 
GeneralGET_TZTIME v3 Pin
robertford11-Jun-09 18:14
robertford11-Jun-09 18:14 
GeneralTime Zone Functions v4 Pin
robertford21-Jan-10 14:35
robertford21-Jan-10 14:35 
Rahul pointed out an issue with the GET_UTCTIME function. I fixed the code and I am reposting it below.

--
-- SQL 2005 Time Zone Conversion setup tables and functions
--
-- Created by: Robert Ford
-- Created on: 11/17/2008
-- Modified on:01/21/2010
-- 
-- 11/17/2008
--	Creation Date
--
-- 11/30/2008
--	Made a modification based upon a note from an Austrailian user of Code project
--	to have an effective and end date in order to have multiple configurations for a single
--	timezone code.  In Austrailia DST dates change often and would require to have the
--	timezone code updated regularly.
--
-- 06/11/2009
--	Made a modification to fix an issue with the code in situations where the DST end range date is
--	in a month that does not start with Sunday.
--
-- 01/21/2010
--	Fixed an issue with the GET_UTCTIME function in regards to time zones that are positive GMT adjusted.
--
-- *************************
--
-- Tables: 
--	TIME_ZONES
--		TIMEZONE_CD 	VARCHAR(6) NOT NULL - this value is used by the functions ot reference the other values
--		TIMEZONE_NAME	VARCHAR(60) NOT NULL - name to describe the time zone code
--		OFFSET_HR	INT NOT NULL - the offset hours for adjusting the date time
--		OFFSET_MI	INT NOT NULL - the offset minutes for adjusting the date time
--		DST_OFFSET_HR	INT NOT NULL - the day light offset hours for adjusting the date time
--		DST_OFFSET_MI	INT NOT NULL - the day light offset minutes for adjusting the date time
--		DST_EFF_DT	VARCHAR(10) NOT NULL - the day light savings effective date time formate: MMWDHHmm
--		DST_END_DT	VARCHAR(10) NOT NULL - the day light savings end date time: MMWDHHmm
--	Notes: This table holds the time zone creterion used to convert date time values
--	DST EFF and END date format: MMWDHHmm
--		MM = two digit month (e.g. March = 3)
--		W = the week of the month (e.g. the second week of the month = 2)
--		D = the day of the week, sunday is the start of the week which starts at 1 (e.g. Monday = 2)
--		HH - two digit hour, 24 hour time (e.g. 2:00 am = 02, and 2:00 pm = 14)
--		mm - two digit minute (e.g. 35 minutes after the hour is 35)
--
--		example: On Sunday on the second week of the month for the month of March at 2:00 am 
--			 would be 03210200
--	
-- Functions: 
--	GET_UTCTIME
--		@DT DATETIME - LOCAL DATETIME
--		@TZ VARCHAR(12) - Time Zone code (must match a value in the database table)
--		Notes: Pass the time zone code and date and the function will 
--		       return a the date in UTC or GMT datetime
--	GET_TZTIME
--		@DT DATETIME - UTC or GMT DATETIME
--		@TZ VARCHAR(12) - Time Zone code (must match a value in the database table)
--		Notes: Pass the GMT or UTC date time and the time zone code
--		       and the function will provide the date time adjusted for the specified
--		       time zone.
--
--	NEW_TIME
--		@DT DATETIME - DATETIME to be converted
--		@TZ1 VARCHAR(12) - Time zone that the date time being passed is in
--		@TZ2 VARCHAR(12) - Time zone to convert the date time to
--		Note: Pass the date time, the time zone code that the date time is in,
--		      and the time zone code that the date time should be converted to.
--		      This function uses the GET_UTCTIME and GET_TZTIME functions
--		      to prepare the value that needs to be delivered.  Supports the use of 
--		      both GMT and UTC codes to represent universal time code or Greenwich Mean Time.
--		
--		
-- Check to see if the table already exists and deletes it if it does

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[TIME_ZONES]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[TIME_ZONES]
GO


-- Create the TIME_ZONES table

CREATE TABLE [dbo].[TIME_ZONES] (
	[TIMEZONE_CD] [varchar] (6) NOT NULL ,
	[TIMEZONE_NAME] [varchar] (60) NOT NULL ,
	[OFFSET_HR] [int] NOT NULL ,
	[OFFSET_MI] [int] NOT NULL ,
	[DST_OFFSET_HR] [int] NOT NULL ,
	[DST_OFFSET_MI] [int] NOT NULL ,
	[DST_EFF_DT] [varchar] (10) NOT NULL ,
	[DST_END_DT] [varchar] (10) NOT NULL ,
	[EFF_DT] DATETIME NOT NULL,
	[END_DT] DATETIME NOT NULL
) ON [PRIMARY]
GO

-- Alter the table to add the primary key
ALTER TABLE [dbo].[TIME_ZONES] WITH NOCHECK ADD 
	CONSTRAINT [PK_TIME_ZONES] PRIMARY KEY  CLUSTERED 
	(
		[TIMEZONE_CD],
		[EFF_DT]
	)  ON [PRIMARY] 
GO

-- Add the field default contraints
ALTER TABLE [dbo].[TIME_ZONES] ADD 
	CONSTRAINT [DF_TIME_ZONES_OFFSET] DEFAULT ((-1)) FOR [OFFSET_HR],
	CONSTRAINT [DF_TIME_ZONES_OFFSET_MI] DEFAULT (0) FOR [OFFSET_MI],
	CONSTRAINT [DF_TIME_ZONES_DST_OFFSET] DEFAULT ((-1)) FOR [DST_OFFSET_HR],
	CONSTRAINT [DF_TIME_ZONES_DST_OFFSET_MI] DEFAULT (0) FOR [DST_OFFSET_MI],
	CONSTRAINT [DF_TIME_ZONES_DST_EFF_DT] DEFAULT ('03210200') FOR [DST_EFF_DT],
	CONSTRAINT [DF_TIME_ZONES_DST_END_DT] DEFAULT ('11110200') FOR [DST_END_DT],
	CONSTRAINT DF_TIME_ZONES_EFF_DT DEFAULT GETDATE() FOR [EFF_DT],
	CONSTRAINT DF_TIME_ZONES_END_DT DEFAULT '12/31/9999' FOR [END_DT]
GO


-- Insert time zone information into the TIME_ZONES table
INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('AKT','Alaskan Time',-9,0,-8,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('AT','Atlantic Time',-4,0,-3,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('AZ','Arizona Time',-7,0,-7,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('CT','Central Time',-6,0,-5,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('ET','Eastern Time',-5,0,-4,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('HT','Hawaii Time',-10,0,-10,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('MT','Mountain Time',-7,0,-6,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('NT','Newfoundland Time',-4,30,-2,30,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('PT','Pacific Time',-8,0,-7,0,'03210200','11110200')
GO

INSERT INTO time_zones(timezone_cd, timezone_name, offset_hr, offset_mi, dst_offset_hr, dst_offset_mi, dst_eff_dt, dst_end_dt)
VALUES('YT','Yukon Time',-8,0,-8,0,'03210200','11110200')
GO

-- =============================================
-- Create scalar function (GET_UTCTIME)
-- =============================================
IF EXISTS (SELECT * 
	   FROM   sysobjects 
	   WHERE  name = N'GET_UTCTIME')
	DROP FUNCTION GET_UTCTIME
GO

CREATE FUNCTION GET_UTCTIME 
	(@DT AS DATETIME, 
	 @TZ AS VARCHAR(12))
RETURNS DATETIME
AS
BEGIN
-- DECLARE VARIABLES
	DECLARE @NEWDT AS DATETIME
	DECLARE @OFFSETHR AS INT
	DECLARE @OFFSETMI AS INT
	DECLARE @DSTOFFSETHR AS INT
	DECLARE @DSTOFFSETMI AS INT
	DECLARE @DSTDT AS VARCHAR(10)
	DECLARE @DSTEFFDT AS VARCHAR(10)
	DECLARE @DSTENDDT AS VARCHAR(10)
	
-- GET THE DST parameter from the provided datetime
	-- This gets the month of the datetime provided (2 char value)
	SELECT @DSTDT = CASE LEN(DATEPART(month, @DT)) WHEN 1 then '0' + CONVERT(VARCHAR(2),DATEPART(month, @DT)) ELSE CONVERT(VARCHAR(2),DATEPART(month, @DT)) END
	-- This gets the occurance of the day of the week within the month (i.e. first sunday, or second sunday...) (1 char value)
	SELECT @DSTDT = @DSTDT + CONVERT(VARCHAR(1),(DATEPART(day,@DT) + 6) / 7)
	-- This gets the day of the week for the provided datetime (1 char value)
	SELECT @DSTDT = @DSTDT + CONVERT(VARCHAR(1),DATEPART(dw, @DT))
	-- This gets the hour for the provided datetime (2 char value)
	SELECT @DSTDT = @DSTDT + CASE LEN(DATEPART(hh, @DT)) WHEN 1 then '0' + CONVERT(VARCHAR(2),DATEPART(hh, @DT)) ELSE CONVERT(VARCHAR(2),DATEPART(hh, @DT)) END
	-- This gets the minutes for the provided datetime (2 char value)
	SELECT @DSTDT = @DSTDT + CASE LEN(DATEPART(mi, @DT)) WHEN 1 then '0' + CONVERT(VARCHAR(2),DATEPART(mi, @DT)) ELSE CONVERT(VARCHAR(2),DATEPART(mi, @DT)) END
	
	-- This query gets the timezone information from the TIME_ZONES table for the provided timezone
	SELECT
		@OFFSETHR=offset_hr,
		@OFFSETMI=offset_mi,
		@DSTOFFSETHR=dst_offset_hr,
		@DSTOFFSETMI=dst_offset_mi,
		@DSTEFFDT=dst_eff_dt,
		@DSTENDDT=dst_END_dt
	FROM time_zones
	WHERE timezone_cd = @TZ AND
		@DT BETWEEN eff_dt AND end_dt
	
	-- Checks to see if the DST parameter for the datetime provided is within the DST parameter for the timezone
	IF @DSTDT BETWEEN @DSTEFFDT AND @DSTENDDT
	BEGIN
		-- Increase the datetime by the hours and minutes assigned to the timezone
		SET @NEWDT = DATEADD(hh,@DSTOFFSETHR*-1,@DT)
		SET @NEWDT = DATEADD(mi,@DSTOFFSETMI*-1,@NEWDT)
	END
	-- If the DST parameter for the provided datetime is not within the defined
	-- DST eff and end dates for the timezone then use the standard time offset
	ELSE
	BEGIN
		-- Increase the datetime by the hours and minutes assigned to the timezone
		SET @NEWDT = DATEADD(hh,@OFFSETHR*-1,@DT)
		SET @NEWDT = DATEADD(mi,@OFFSETMI*-1,@NEWDT)
	END

	-- Return the new date that has been converted to UTC time
	RETURN @NEWDT
END
GO

-- =============================================
-- Create scalar function (GET_TZTIME)
-- =============================================
IF EXISTS (SELECT * 
	   FROM   sysobjects 
	   WHERE  name = N'GET_TZTIME')
	DROP FUNCTION GET_TZTIME
GO

CREATE FUNCTION [dbo].[GET_TZTIME] 
	(@DT AS DATETIME, 
	 @TZ AS VARCHAR(12))
RETURNS DATETIME
AS
BEGIN
-- DECLARE VARIABLES
	DECLARE @NEWDT AS DATETIME
	DECLARE @OFFSETHR AS INT
	DECLARE @OFFSETMI AS INT
	DECLARE @DSTOFFSETHR AS INT
	DECLARE @DSTOFFSETMI AS INT
	--DECLARE @DSTDT AS VARCHAR(10)
	DECLARE @DSTEFFDT AS VARCHAR(10)
	DECLARE @DSTENDDT AS VARCHAR(10)
	DECLARE @DSTSTARTDT AS DATETIME
	DECLARE @DSTSTOPDT AS DATETIME
	
	-- This query gets the timezone information from the TIME_ZONES table for the provided timezone
	SELECT
		@OFFSETHR=offset_hr,
		@OFFSETMI=offset_mi,
		@DSTOFFSETHR=dst_offset_hr,
		@DSTOFFSETMI=dst_offset_mi,
		@DSTEFFDT=dst_eff_dt,
		@DSTENDDT=dst_END_dt
	FROM time_zones
	WHERE timezone_cd = @TZ AND
		@DT BETWEEN eff_dt AND end_dt

	-- Increase the datetime by the hours and minutes assigned to the timezone
	SET @NEWDT = DATEADD(hh,@OFFSETHR,@DT)
	SET @NEWDT = DATEADD(mi,@OFFSETMI,@NEWDT)

	-- Declare variables needed to convert MMWDHHmm pattern to  for DST start date
	DECLARE @DSTSTARTMONTH INT
	DECLARE @DSTSTARTINSTANCE INT
	DECLARE @DSTSTARTDAY INT
	DECLARE @DSTSTARTHOUR INT
	DECLARE @DSTSTARTMINUTE INT
	DECLARE @DSTSTARTMODIFIER INT

	-- Perform calculations to determine date
	SET @DSTSTARTMONTH = CONVERT(INT,SUBSTRING(@DSTEFFDT,1,2))-1
	SET @DSTSTARTINSTANCE = CONVERT(INT,SUBSTRING(@DSTEFFDT,3,1))
	SET @DSTSTARTDAY = CONVERT(INT,SUBSTRING(@DSTEFFDT,4,1))
	SET @DSTSTARTHOUR = CONVERT(INT,SUBSTRING(@DSTEFFDT,5,2))
	SET @DSTSTARTMINUTE = CONVERT(INT,SUBSTRING(@DSTEFFDT,7,2))
	-- Set the start date variable to the first day of the year for the year of the date being evaluated
	SET @DSTSTARTDT = CONVERT(DATETIME,'1/1/' + CONVERT(VARCHAR(4),DATEPART(year,@NEWDT)))
	-- Add month value for start pattern to the start date variable
	SET @DSTSTARTDT = DATEADD(month,@DSTSTARTMONTH,@DSTSTARTDT)
	-- Determine the modifier value needed to adjust the date when the date desired is in a 
	-- month that does not start on a Sunday
	SET @DSTSTARTMODIFIER = DATEPART(weekday,@DSTSTARTDT)

	-- Check to see if the modifier date is greater than the date being evaluated
	-- This is important because it will change the final modifier
	-- (adding days in some instances and subtracting days in others
	IF @DSTSTARTMODIFIER > @DSTSTARTDAY
	BEGIN
		SET @DSTSTARTMODIFIER = 8 - @DSTSTARTMODIFIER
	END
	ELSE
	BEGIN
		SET @DSTSTARTMODIFIER = (@DSTSTARTMODIFIER-1)*-1
	END

	-- This is the main calculation to determine the date of the MMWDHHmm pattern
	SET @DSTSTARTDT = DATEADD(day,(@DSTSTARTINSTANCE*7)-(8-@DSTSTARTDAY) + @DSTSTARTMODIFIER,@DSTSTARTDT)
	SET @DSTSTARTDT = DATEADD(hour,@DSTSTARTHOUR,@DSTSTARTDT)
	SET @DSTSTARTDT = DATEADD(minute,@DSTSTARTMINUTE,@DSTSTARTDT)

	-- Declare variables needed to convert MMWDHHmm pattern to  for DST stop date
	DECLARE @DSTSTOPMONTH INT
	DECLARE @DSTSTOPINSTANCE INT
	DECLARE @DSTSTOPDAY INT
	DECLARE @DSTSTOPHOUR INT
	DECLARE @DSTSTOPMINUTE INT
	DECLARE @DSTSTOPMODIFIER INT

	-- Perform calculations to determine date
	SET @DSTSTOPMONTH = CONVERT(INT,SUBSTRING(@DSTENDDT,1,2))-1
	SET @DSTSTOPINSTANCE = CONVERT(INT,SUBSTRING(@DSTENDDT,3,1))
	SET @DSTSTOPDAY = CONVERT(INT,SUBSTRING(@DSTENDDT,4,1))
	SET @DSTSTOPHOUR = CONVERT(INT,SUBSTRING(@DSTENDDT,5,2))
	SET @DSTSTOPMINUTE = CONVERT(INT,SUBSTRING(@DSTENDDT,7,2))
	-- Set the start date variable to the first day of the year for the year of the date being evaluated
	SET @DSTSTOPDT = CONVERT(DATETIME,'1/1/' + CONVERT(VARCHAR(4),DATEPART(year,@NEWDT)))
	-- Determine the modifier value needed to adjust the date when the date desired is in a 
	SET @DSTSTOPDT = DATEADD(month,@DSTSTOPMONTH,@DSTSTOPDT)
	-- Determine the modifier value needed to adjust the date when the date desired is in a 
	-- month that does not start on a Sunday
	SET @DSTSTOPMODIFIER = DATEPART(weekday,@DSTSTOPDT)

	-- Check to see if the modifier date is greater than the date being evaluated
	-- This is important because it will change the final modifier
	-- (adding days in some instances and subtracting days in others
	IF @DSTSTOPMODIFIER > @DSTSTOPDAY
	BEGIN
		SET @DSTSTOPMODIFIER = 8 - @DSTSTOPMODIFIER
	END
	ELSE
	BEGIN
		SET @DSTSTOPMODIFIER = (@DSTSTOPMODIFIER-1)*-1
	END
	
	-- This is the main calculation to determine the date of the MMWDHHmm pattern
	SET @DSTSTOPDT = DATEADD(day,(@DSTSTOPINSTANCE*7)-(8-@DSTSTOPDAY) + @DSTSTOPMODIFIER,@DSTSTOPDT)
	SET @DSTSTOPDT = DATEADD(hour,@DSTSTOPHOUR,@DSTSTOPDT)
	SET @DSTSTOPDT = DATEADD(minute,@DSTSTOPMINUTE,@DSTSTOPDT)

	-- Check to see if the date being evaluated falls between the 
	-- DST start and stop date/times
	IF @NEWDT BETWEEN @DSTSTARTDT AND @DSTSTOPDT
	BEGIN
		-- Increase the datetime by the hours and minutes assigned to the timezone
		SET @NEWDT = DATEADD(hh,@DSTOFFSETHR,@DT)
		SET @NEWDT = DATEADD(mi,@DSTOFFSETMI,@NEWDT)
	END

	-- Return the new date that has been converted from UTC time
	RETURN @NEWDT
END
GO


-- =============================================
-- Create scalar function (NEW_TIME)
-- =============================================
IF EXISTS (SELECT * 
	   FROM   sysobjects 
	   WHERE  name = N'NEW_TIME')
	DROP FUNCTION NEW_TIME
GO

CREATE FUNCTION NEW_TIME 
	(@DT AS DATETIME, 
	 @TZ1 AS VARCHAR(12),
	 @TZ2 AS VARCHAR(12))
RETURNS DATETIME
AS
BEGIN
	-- Declare variables
	DECLARE @NEWDT AS DATETIME
	
	-- Check to see if the provided timezone for the source datetime is in GMT or UTC time
	-- If it is not then convert the provided datetime to UTC time
	IF NOT @TZ1 IN ('GMT','UTC')
	BEGIN
		SELECT @NEWDT = dbo.GET_UTCTIME(@DT,@TZ1)
	END
	ELSE
	-- If the provided datetime is in UTC or GMT time then set the NEWTIME variable to this value
	BEGIN
		SET @NEWDT = @DT
	END

	-- Check to see if the provided conversion timezone is GMT or UTC
	-- If it is then no conversion is needed.
	-- If it is not then convert the provided datetime to the desired timezone
	IF NOT @TZ2 IN ('GMT','UTC')
	BEGIN
		SELECT @NEWDT = dbo.GET_TZTIME(@NEWDT,@TZ2)
	END

	-- Return the new converted datetime
	RETURN @NEWDT
	
END
GO


Robert Ford

GeneralTime Zone Functions v5 Pin
robertford2-Apr-10 18:05
robertford2-Apr-10 18:05 
GeneralRe: Time Zone Functions v5 [modified] Pin
shell_l_d20-Jul-10 19:31
shell_l_d20-Jul-10 19:31 
GeneralRe: Time Zone Functions v5 Pin
robertford21-Jul-10 3:19
robertford21-Jul-10 3:19 
GeneralRe: Time Zone Functions v5 [modified] Pin
shell_l_d21-Jul-10 4:18
shell_l_d21-Jul-10 4:18 
GeneralRe: Time Zone Functions v5 Pin
shell_l_d21-Jul-10 16:13
shell_l_d21-Jul-10 16:13 
AnswerRe: Time Zone Functions v5 [modified] Pin
shell_l_d22-Jul-10 5:09
shell_l_d22-Jul-10 5:09 
GeneralRe: Time Zone Functions v5 Pin
Callon Campbell4-Aug-10 4:22
Callon Campbell4-Aug-10 4:22 
GeneralRe: Time Zone Functions v5 [modified] Pin
shell_l_d4-Aug-10 17:42
shell_l_d4-Aug-10 17:42 
GeneralRe: Time Zone Functions v5 Pin
robertford6-Aug-10 5:53
robertford6-Aug-10 5:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.