Accounting for DST in Postgres, when selecting scheduled items

后端 未结 3 1759
渐次进展
渐次进展 2020-12-08 05:31

I have a Postgres table of clock alarms (not really, but this is analogous, and easier to explain). Alarms are set by users with a 1 hour r

3条回答
  •  孤城傲影
    2020-12-08 06:25

    You would do it by using a full time zone name, e.g. America/New_York rather than EDT/EST, and storing the hour in that time zone not UTC. You can then remain blissfully ignorant of the offset changes for daylight savings.

    Something like the following should work:

    -- CREATE TABLE time_test (
    --   user_to_alert CHARACTER VARYING (30),
    --   alarm_hour TIME,
    --   user_timezone CHARACTER VARYING (30)
    -- );
    
    SELECT user_to_alert, 
      CASE
        WHEN EXTRACT(HOUR FROM CURRENT_TIME AT TIME ZONE user_timezone) = EXTRACT(HOUR FROM alarm_hour) THEN TRUE
      ELSE FALSE
    END AS raise_alarm
    FROM time_test;
    

    Or:

    SELECT user_to_alert
    FROM time_test
    WHERE EXTRACT(HOUR FROM CURRENT_TIME AT TIME ZONE user_timezone) = EXTRACT(HOUR FROM alarm_hour);
    

提交回复
热议问题