2

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

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

4

2 回答 2

6

我在 SQL Server中使用了这个由 Tim Cullen 创建的夏令时函数。

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

开始日期功能

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
于 2013-03-22T06:42:55.593 回答
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
于 2017-08-25T08:04:05.770 回答