What is an appropriate data type to store a timezone?

后端 未结 5 1890
情深已故
情深已故 2021-02-03 22:55

I\'m thinking of simply using a string in the format \"+hh:mm\" (or \"-hh:mm\"). Is this both necessary and sufficient?

Note: I don\'t need to store the date or the time

5条回答
  •  生来不讨喜
    2021-02-03 23:16

    In an ideal world you could have a foreign key to a set of known timezones. You can do something close to this with views and domains.

    This wiki tip by David E. Wheleer creates a domain that is tested for its validity as a timezone:

    CREATE OR REPLACE FUNCTION is_timezone( tz TEXT ) RETURNS BOOLEAN as $$
    BEGIN
     PERFORM now() AT TIME ZONE tz;
     RETURN TRUE;
    EXCEPTION WHEN invalid_parameter_value THEN
     RETURN FALSE;
    END;
    $$ language plpgsql STABLE;
    
    CREATE DOMAIN timezone AS CITEXT
    CHECK ( is_timezone( value ) );
    

    It's useful to have a list of known timezones, in which case you could dispense with the domain and just enforce the constraint in the one table containing the known timezone names (obtained from the view pg_timezone_names), avoiding the need to expose the domain elsewhere:

    CREATE TABLE tzone
    (
      tzone_name text PRIMARY KEY (tzone_name) CHECK (is_timezone(tzone_name))
    );
    
    INSERT INTO tzone (tzone_name)
    SELECT name FROM pg_timezone_names;
    

    Then you can enforce correctness through foreign keys:

    CREATE TABLE myTable (
    ...
    tzone TEXT REFERENCES tzone(tzone_name)
    );
    

提交回复
热议问题