Specify a time zone to use as the reference time zone

后端 未结 4 1777
鱼传尺愫
鱼传尺愫 2021-01-07 09:06

Based on the first two answers, the question was unclear as originally posted, thus I am completely rewriting it:

The following question is concerned only w

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 09:27

    You have to save the time zone offset in addition to the timestamp.

    As @Milen already explained (and linked to the manual): a timestamp only saves a point in time (as abstract value). The time zone modifier is not saved, it only serves to adjust the timestamp relative to UTC.

    Consider the following demo:

    -- DROP TABLE tbl;
    CREATE TEMP TABLE tbl (id int, myts timestamptz, mytz interval);
    
    INSERT INTO tbl VALUES
     (1, now()                , EXTRACT (timezone from now()) * interval '1s')
    ,(2, '2012-01-01 00:00-05', interval '-5h')
    ,(3, '2012-01-01 00:00+04', interval '4h')
    ,(4, '2012-11-11 20:30+03', interval '3h');
    
    SELECT *
          ,(myts AT TIME ZONE mytz)::text
           || CASE WHEN mytz > '0:0' THEN '+' ELSE '' END
           || to_char(mytz, 'FMHH24:mi') AS timestamp_at_origin
    FROM tbl;
    

    Run it locally to see. Pay special attention to the details of the AT TIME ZONE construct, and how I extract the time zone from the (local!) timestamp with time zone.
    now() returns timestamp with time zone or timestamptz for short.

    EXTRACT (timezone from now()) * interval '1s'
    

    timestamp_at_origin displays the timestamp with time zone as seen at its origin. If I understood your question, then that is what you are looking for.
    You could further improve formatting.

    You may be interested in this related question which sheds some light on the ambiguities and pitfalls of time zones.

提交回复
热议问题