In Postgresql, how to un-invert the timezone offsets with “At Time Zone”

久未见 提交于 2019-12-23 13:07:56

问题


I'm trying to wrap my head around Postgresql timezones, and I can't seem to figure this out. EST is "Eastern Standard Time" in America, and is typically UTC-5.

Example 1: Base Test

select '08/31/2011 12:00 pm EST'::timestamptz  at time zone 'EST';
      timezone       
---------------------
 2011-08-31 12:00:00

Example 2: Offset is +5

select '08/31/2011 12:00 pm EST' at time zone '+5';
      timezone       
---------------------
 2011-08-31 12:00:00

Example 3: Offset is -5

 select '08/31/2011 12:00 pm EST' at time zone '-5';
      timezone       
---------------------
 2011-08-31 22:00:00

Clearly, everything is backwards. EST is again... supposed to be UTC-5. Now, I did search through documentation, and it does explain that things are "POSIX", which is backwards. (Positive offset is west of GMT, while negative offsets are east of GMT).

However, how do I get around this? At the application layer, I can always invert the + sign to a - sign, but that seems a bit messy to me IMO. Thus, my ultimate question.

At the database layer (Postgres), is there a way to use the "At Time Zone" syntax so that GMT-5 corresponds to EST? Or do I just have to invert everything at the application layer?


回答1:


Use interval datatype as written in documentation to get proper behaviour:

In these expressions, the desired time zone zone can be specified either as a text string (e.g., 'PST') or as an interval (e.g., INTERVAL '-08:00').

Base test:

SELECT '08/31/2011 12:00 pm EST'::timestamptz AT TIME ZONE 'EST';
      timezone       
---------------------
 2011-08-31 12:00:00
(1 row)

Timezone info:

SELECT * FROM pg_timezone_abbrevs WHERE abbrev LIKE 'EST';
 abbrev | utc_offset | is_dst 
--------+------------+--------
 EST    | -05:00:00  | f
(1 row)

Proper offset -5:

SELECT '08/31/2011 12:00 pm EST'::timestamptz AT TIME ZONE '-05:00'::interval;
      timezone       
---------------------
 2011-08-31 12:00:00
(1 row)

Proper offset +5:

SELECT '08/31/2011 12:00 pm EST'::timestamptz AT TIME ZONE '+05:00'::interval;
      timezone       
---------------------
 2011-08-31 22:00:00
(1 row) 


来源:https://stackoverflow.com/questions/7117355/in-postgresql-how-to-un-invert-the-timezone-offsets-with-at-time-zone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!