I have a PostgreSQL database where the timestamps are stored like this:
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).
I am needing to retrieve the dates in whatever time zone it currently is (EST or EDT), regardless of how it was saved. This must be done in PostgreSQL and not on the front-end.
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?
CodePudding user response:
Assuming your server has a TimeZone
that covers EST/EDT
:
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
CodePudding user response:
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 11:00:00
- 2022-12-22 10:00:00
For timestamp with time zone, the internally stored value is always in UTC. When a timestamp with time zone value is output, it is always converted from UTC to the current timezone zone