检查夏令时是打开还是关闭

时间:2013-03-22 06:26:55

标签: sql-server sql-server-2008 stored-procedures dst

在某种情况下,我必须检查夏令时是否有效。根据检查的结果,我必须在SQL服务器过程中进行一些计算。

快速检查夏令时是否有效的最佳方法是什么?

2 个答案:

答案 0 :(得分:5)

我使用了由Tim Cullen创建的Daylight Savings Time Functions in SQL Server

具体来说,我使用的代码是:

开始日期功能

CREATE function [dbo].[fn_GetDaylightSavingsTimeStart]
(@Year varchar(4))
RETURNS smalldatetime
as
begin
declare @DTSStartWeek smalldatetime, @DTSEndWeek smalldatetime
set @DTSStartWeek = '03/01/' + convert(varchar,@Year)
return case datepart(dw,@DTSStartWeek)
when 1 then
dateadd(hour,170,@DTSStartWeek)
when 2 then
dateadd(hour,314,@DTSStartWeek)
when 3 then 
dateadd(hour,290,@DTSStartWeek)
when 4 then 
dateadd(hour,266,@DTSStartWeek)
when 5 then 
dateadd(hour,242,@DTSStartWeek)
when 6 then 
dateadd(hour,218,@DTSStartWeek)
when 7 then
dateadd(hour,194,@DTSStartWeek)
end
end

结束日期功能

CREATE function [dbo].[fn_GetDaylightSavingsTimeEnd]
(@Year varchar(4))
RETURNS smalldatetime
as
begin
declare @DTSEndWeek smalldatetime
set @DTSEndWeek = '11/01/' + convert(varchar,@Year)
return case datepart(dw,dateadd(week,1,@DTSEndWeek))
when 1 then
dateadd(hour,2,@DTSEndWeek)
when 2 then
dateadd(hour,146,@DTSEndWeek)
when 3 then
dateadd(hour,122,@DTSEndWeek)
when 4 then
dateadd(hour,98,@DTSEndWeek)
when 5 then 
dateadd(hour,74,@DTSEndWeek)
when 6 then 
dateadd(hour,50,@DTSEndWeek)
when 7 then 
dateadd(hour,26,@DTSEndWeek)
end
end

然后我在我的查询中使用这样的函数:

declare @DLSStart smalldatetime 
, @DLSEnd smalldatetime 
, @DLSActive tinyint 
set @DLSStart = (select MSSQLTIPS.dbo.fn_GetDaylightSavingsTimeStart(convert(varchar,datepart(year,getdate()))))
set @DLSEnd = (select MSSQLTIPS.dbo.fn_GetDaylightSavingsTimeEnd(convert(varchar,datepart(year,getdate())))) 

if @Date between @DLSStart and @DLSEnd 
begin 
set @DLSActive = 1 
end 
else 
begin 
set @DLSActive = 0 
end 
select @DLSActive

答案 1 :(得分:0)

在西欧,夏季时间从3月的最后一个星期日02:00开始

select 
DATEADD(
    day,
    DATEDIFF(
        day,
        '1900-01-07',
        DATEADD(month,DATEDIFF(MONTH,0,concat(year(getdate()),'-03-01')),30)
        )/7*7,
    '1900-01-07 02:00'
    ) as SummerTimeStarts

并于10月的最后一个星期日03:00结束

Select 
DATEADD(
    day,
    DATEDIFF(
        day,
        '1900-01-07',
        DATEADD(month,DATEDIFF(MONTH,0,concat(year(getdate()),'-10-01')),30)
        )/7*7,
    '1900-01-07 03:00'
    ) as SummerTimeEnds

它给出了en函数:

CREATE function [dbo].[DateIsSummerTime]
(@datetime datetime)
RETURNS bit
as
begin
    declare @SummerTimeStarts datetime, @SummerTimeEnds datetime
    set @SummerTimeStarts = (select DATEADD(day,DATEDIFF(day,'1900-01-07',DATEADD(month,DATEDIFF(MONTH,0,concat(year(getdate()),'-03-01')),30))/7*7,'1900-01-07 02:00'))
    set @SummerTimeEnds   = (Select DATEADD(day,DATEDIFF(day,'1900-01-07',DATEADD(month,DATEDIFF(MONTH,0,concat(year(getdate()),'-10-01')),30))/7*7,'1900-01-07 03:00')) 

    Return  Case when @datetime > @SummerTimeStarts and @datetime < @SummerTimeEnds then 1 else 0 end
end