Reputation: 307
What is standard time that SQL Server returns using 'datediff' function?
datediff(ss, '1/1/1970', current_timestamp)
Is it GMT ?
Requirement :
User-defined function to return the Timestamp in CST and DST time stamps depends on the current time (CST or day light saving).
In CST time zone i,e 'CST Time in the zone is six hours behind GMT'
(datediff(ss, '1/1/1970', current_timestamp) + 21600)
During daylight saving time (DST), time in the zone is five hours behind GMT
(datediff(ss, '1/1/1970', current_timestamp) + 18000)
Can anyone help me to create a user defined function for the above requirement.
Thanks & regards, Venkat
Upvotes: 0
Views: 2010
Reputation: 96
Not clear what you're asking, but if you want to convert UTC to CST try this function using "-6" as your UTC offset.
---------------------------------------------------------------------------------------------------
--Name: udfToLocalTime.sql
--Purpose: To convert UTC to local US time accounting for DST
--Author: Patrick Slesicki
--Date: 3/25/2014
--Notes: Tested on SQL Server 2008R2 and later.
-- Good only for US States observing the Energy Policy Act of 2005.
-- Function doesn't apply for years prior to 2007.
-- Function assumes that the 1st day of the week is Sunday.
--Tests:
-- SELECT dbo.udfToLocalTime('2014-03-09 9:00', DEFAULT)
-- SELECT dbo.udfToLocalTime('2014-03-09 10:00', DEFAULT)
-- SELECT dbo.udfToLocalTime('2014-11-02 8:00', DEFAULT)
-- SELECT dbo.udfToLocalTime('2014-11-02 9:00', DEFAULT)
---------------------------------------------------------------------------------------------------
ALTER FUNCTION udfToLocalTime
(
@UtcDateTime AS DATETIME
,@UtcOffset AS INT = -8 --PST
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@MyDateTime AS DATETIME
,@Year AS CHAR(4)
,@MarTime AS TIME
,@NovTime AS TIME
,@Mar1 AS DATETIME
,@Nov1 AS DATETIME
,@Mar1Day AS INT
,@Nov1Day AS INT
,@MarDiff AS INT
,@NovDiff AS INT
,@DstStart AS DATETIME
,@DstEnd AS DATETIME
SELECT
@Year = CONVERT(CHAR(4), YEAR(@UtcDateTime))
,@MarTime = CONVERT(TIME, DATEADD(HOUR, -@UtcOffset, '1900-01-01 02:00'))
,@NovTime = CONVERT(TIME, DATEADD(HOUR, -@UtcOffset - 1, '1900-01-01 02:00'))
,@Mar1 = CONVERT(CHAR(16), @Year + '-03-01 ' + CONVERT(CHAR(5), @MarTime), 126)
,@Nov1 = CONVERT(CHAR(16), @Year + '-11-01 ' + CONVERT(CHAR(5), @NovTime), 126)
,@Mar1Day = DATEPART(WEEKDAY, @Mar1)
,@Nov1Day = DATEPART(WEEKDAY, @Nov1)
--Get number of days between Mar 1 and DST start date
IF @Mar1Day = 1 SET @MarDiff = 7
ELSE SET @MarDiff = 15 - @Mar1Day
--Get number of days between Nov 1 and DST end date
IF @Nov1Day = 1 SET @NovDiff = 0
ELSE SET @NovDiff = 8 - @Nov1Day
--Get DST start and end dates
SELECT
@DstStart = DATEADD(DAY, @MarDiff, @Mar1)
,@DstEnd = DATEADD(DAY, @NovDiff, @Nov1)
--Change UTC offset if @UtcDateTime is in DST Range
IF @UtcDateTime >= @DstStart AND @UtcDateTime < @DstEnd SET @UtcOffset = @UtcOffset + 1
--Get Conversion
SET @MyDateTime = DATEADD(HOUR, @UtcOffset, @UtcDateTime)
RETURN @MyDateTime
END
GO
Upvotes: 2