Detect if a date is in Daylight saving time in MySql

前端 未结 4 655
失恋的感觉
失恋的感觉 2021-01-25 09:32

I have inherited a legacy application where all the dates and times are stored in the local timezone (UK). I am not in a position to change how these are stored.

Howeve

4条回答
  •  不要未来只要你来
    2021-01-25 10:24

    As an alternative, here are some functions to determine whether the North American Daylight Savings rules are in effect.

    As of 2007* the rule in North America has been that Daylight Savings (DST):

    • starts at 2am (local time) on the 2nd Sunday of March
    • ends at 2am (local time) on the 1st Sunday of November

    *(From 1987 to 2006 it was the April's 1st Sunday to October's last Sunday.)


    MySQL Functions:

    DELIMITER // CREATE FUNCTION DSTstart(dt DATETIME) RETURNS DATETIME DETERMINISTIC BEGIN 
    RETURN cast(concat(year(now()),'-3-',(14-WEEKDAY(concat(year(now()),'-3-1'))),' 2:00') as datetime);
    END// DELIMITER ;
    
    DELIMITER // CREATE FUNCTION DSTstop(dt DATETIME) RETURNS DATETIME DETERMINISTIC BEGIN 
    RETURN cast(concat(year(now()),'-11-',(7-WEEKDAY(concat(year(now()),'-11-1'))),' 2:00') as datetime);
    END// DELIMITER ;
    
    DELIMITER // CREATE FUNCTION isDST(dt DATETIME) RETURNS BIT DETERMINISTIC BEGIN 
    RETURN (dt>=cast(concat(year(now()),'-3-',(14-WEEKDAY(concat(year(now()),'-3-1'))),' 2:00') as datetime))
    AND (dt

    Just for reference I'll include the VBA and Excel Worksheet versions of the functions:

    Excel/Access/etc VBA Functions:

    Function DSTstart(dt As Date) As Date 
      DSTstart = CDate(Year(dt) & "-3-" & (15 - Weekday(CDate(Year(dt) & "-3-1"), 2)) & " 2:00")
    End Function
    
    Function DSTstop(dt As Date) As Date 
      DSTstop = CDate(Year(dt) & "-11-" & (8 - Weekday(CDate(Year(dt) & "-11-1"), 2)) & " 2:00")
    End Function
    
    Function isDST(dt As Date) As Boolean
      isDST = (dt >= CDate(Year(dt) & "-3-" & (15 - Weekday(CDate(Year(dt) & "-3-1"), 2)) & " 2:00") _
              And dt < CDate(Year(dt) & "-11-" & (8 - Weekday(CDate(Year(dt) & "-11-1"), 2)) & " 2:00"))
    End Function
    

    Excel Worksheet Functions:

    DST Start: (returns the date/time that DST begins in the year of the date in [A1])

    =DATE(YEAR(A1),3,15-WEEKDAY(DATE(YEAR(A1),3,1),2))+TIMEVALUE("2:00")
    

    DST End: (returns the date/time that DST begins in the year of the date in [A1])

    =DATE(YEAR(A1),11,8-WEEKDAY(DATE(YEAR(A1),11,1),2))+TIMEVALUE("2:00")
    

    Is DST?: (returns TRUE if DST is in effect for the date in [A1])

    =AND(A1>=DATE(YEAR(A1),3,15-WEEKDAY(DATE(YEAR(A1),3,1),2))+TIMEVALUE("2:00"),A1

提交回复
热议问题