简体   繁体   English

如何补偿夏时制 PostgreSQL

[英]How to compensate for daylight savings time PostgreSQL

I have a PostgreSQL database where the timestamps are stored like this:我有一个 PostgreSQL 数据库,其中时间戳存储如下:

6/22/2022 11:00:00 AM EST

or或者

12/22/2022 11:00:00 AM EDT

They are being saved as type TIMESTAMP(6).它们被保存为类型 TIMESTAMP(6)。

I am needing to retrieve the dates in whatever time zone it currently is (EST or EDT), regardless of how it was saved.无论它是如何保存的,我都需要在当前的任何时区(EST 或 EDT)中检索日期。 This must be done in PostgreSQL and not on the front-end.这必须在 PostgreSQL 而不是前端完成。

Every answer I have seen mentions that a simple change in how the data is stored is the best solution.我看到的每个答案都提到,数据存储方式的简单改变是最好的解决方案。 In my case, changing how the dates are already stored and how they will be stored going forward is not an option, so I must find another way.就我而言,更改日期已存储的方式以及以后如何存储它们不是一种选择,因此我必须找到另一种方法。

Is this even possible?这甚至可能吗?

Assuming your server has a TimeZone that covers EST/EDT :假设您的服务器有一个涵盖EST/EDT TimeZone


show timezone;
     TimeZone     
------------------
 America/New_York


select '6/22/2022 11:00:00'::timestamp::timestamptz;
      timestamptz       
------------------------
 2022-06-22 11:00:00-04


select '12/22/2022 11:00:00'::timestamp::timestamptz;
      timestamptz       
------------------------
 2022-12-22 11:00:00-05

To convert to formatted string:要转换为格式化字符串:


select to_char('12/22/2022 11:00:00'::timestamp::timestamptz, 'MM/DD/YYYY HH:MI:SS AM TZ');
          to_char           
----------------------------
 12/22/2022 11:00:00 AM EST

An example using your input:使用您的输入的示例:

SELECT  t AS input
    , t at time zone 'EDT' AS edt
    , t at time zone 'EST' AS est
FROM    (VALUES('12/22/2022 11:00:00 AM EDT'::timestamptz)) s(t);

This is what I get as output:这就是我得到的输出:

  • 2022-12-22 16:00:00+01 2022-12-22 16:00:00+01
  • 2022-12-22 11:00:00 2022-12-22 11:00:00
  • 2022-12-22 10:00:00 2022-12-22 10:00:00

For timestamp with time zone, the internally stored value is always in UTC.对于带时区的时间戳,内部存储的值始终为 UTC。 When a timestamp with time zone value is output, it is always converted from UTC to the current timezone zone输出带有时区值的时间戳时,总是从 UTC 转换为当前时区

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM