Skip to content

Instantly share code, notes, and snippets.

@karoltheguy
Created April 21, 2017 17:26
Show Gist options
  • Select an option

  • Save karoltheguy/ed065b89daf534b2b4a3965ea93e14d3 to your computer and use it in GitHub Desktop.

Select an option

Save karoltheguy/ed065b89daf534b2b4a3965ea93e14d3 to your computer and use it in GitHub Desktop.
Determine if given date is within DST clock shift - SQL Scalar Function
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Carol Ouellet
-- Create date: 2017-04-21
-- Description: Determine if given date is within DST clock shift
-- =============================================
CREATE FUNCTION IsDaylightSavingTime
(
-- Add the parameters for the function here
@DateToCheck varchar(255)
)
RETURNS BIT
AS
BEGIN
-- Declare the return variable here
DECLARE @IsDST BIT
-- Add the T-SQL statements to compute the return value here
Declare @DstEnd datetime;
with FirstWeekOfNovember
as (
select top(7)
cast(YEAR(@DateToCheck) as char(4))
+ '-11-0'
+ cast(row_number() over(order by object_id) as char(1))
+ ' 02:00:00'
'DST_Stops'
from sys.columns
)
select @DstEnd = DST_Stops
from FirstWeekOfNovember
where datepart(weekday,DST_Stops) = 1
Declare @DstStart datetime;
;with FirstWeekOfNovember
as (
select top(7)
cast(Year(@DateToCheck) as char(4))
+ '-11-0'
+ cast(row_number() over(order by object_id) as char(1))
+ ' 02:00:00'
'DST_Stops'
from sys.columns
)
select @DstStart = dateadd(day,-238,DST_Stops)
from FirstWeekOfNovember
where datepart(weekday,DST_Stops) = 1
-- Return the result of the function
RETURN CASE
WHEN @DateToCheck > @DstStart AND @DateToCheck < @DstEnd THEN 1
ELSE 0
END
END
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment