Determine if daylight saving time is active? SQL Server

人盡茶涼 提交于 2019-12-02 10:09:39

问题


I have a table with users, UTC time offset, and if they observe daylight saving time. Is there a built in way to get the correct user time?


回答1:


Right now I'm doing this:

SELECT 
CASE USEDAYLIGHTSAVING
    WHEN 1 THEN
        CASE DATEDIFF(HH,GETUTCDATE(),GETDATE())
                -- I know the server is set to Mountan time and follows daylight saving time
                -- MDT = -6
                -- MST = -7
            WHEN -6 THEN 
                DATEADD(HH,TIMEZONEOFFSET+1,GETUTCDATE())
            ELSE 
                DATEADD(HH,TIMEZONEOFFSET,GETUTCDATE())
        END
    ELSE
            DATEADD(HH,TIMEZONEOFFSET,GETUTCDATE())
    END
FROM 
USERS

It works but if the server get's moved to another timezone or doesn't fallow daylight saving time I'm hosed.




回答2:


I have a table with users, UTC time offset, and if they observe daylight saving time. Is there a built in way to get the correct user time?

Different time zones around the world observe DST in different ways. They start and stop at different times of the day. Simply having an offset and DST flag is not enough to reliably convert.

Instead, you need a time zone identifier, such as America/Los_Angeles, or one of the others listed here. Once you have that, you can use my SQL Server Time Zone Support project to do the conversions.




回答3:


This won't work in all cases, but is a quick fix for those in the US w/ DST defined as between the 2nd Sunday of March and the 1st Sunday of November.

DECLARE @Date datetime2 = '2018-11-04 02:01:00'

SELECT 
    CASE 
        WHEN @Date between
            DATETIMEFROMPARTS(YEAR(@Date), 3, (8 - DATEPART(WEEKDAY, DATEFROMPARTS(YEAR(@Date), 3, 1))) + 8, 02, 00, 00, 00)
            and
            DATETIMEFROMPARTS(YEAR(@Date), 11, (8 - DATEPART(WEEKDAY, DATEFROMPARTS(YEAR(@Date), 11, 1))) + 1, 02, 00, 00, 00)
        THEN 1
        ELSE 0
    END --Is it dst?



回答4:


The sys.time_zone_info table introduced in SQL 2016 allows to determine the offset from UTC and whether DST is currently in effect.

SELECT * FROM sys.time_zone_info

The query result will be:



来源:https://stackoverflow.com/questions/6781121/determine-if-daylight-saving-time-is-active-sql-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!