What is an appropriate data type to store a timezone?

后端 未结 5 1892
情深已故
情深已故 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:13

    In postgres, you can already cast any TIMESTAMP or TIMESTAMPTZ to or from a named timezone, so you don't need to look up values from a table. You can use this expression directly in a check constraint, so you don't need to create a function for this either:

    CREATE TABLE locations (
        location_id SERIAL PRIMARY KEY,
        name TEXT,
        timezone TEXT NOT NULL CHECK (now() AT TIME ZONE timezone IS NOT NULL)
    );
    

    If you try to insert a value that does not contain a valid timezone, you'll get an error that is actually rather user friendly:

    INSERT INTO locations (name, timezone) VALUES ('foo', 'Adelaide/Australia');
    ERROR:  time zone "Adelaide/Australia" not recognized
    

    Depending upon your requirements, you might need the error to be in the format that a normal constraint violation would provide you, however in many cases this will suffice.

    If you are using a web framework that provides you with a list of timezones that you can have in a dropdown box, then this validation should be sufficient, and then your check constraint is just a backup.

提交回复
热议问题