Skip to content
Advertisement

Reading and Writing UTC to TIMESTAMP in Postgresql

I have a Java application that inserts data into a database using prepared statements. In the preparedStamement date is set in UTC format.

preparedStatement.setDate(index, new java.sql.Date(date.getTime()), UTC);

I want to be sure that when read and write operations execute on the table, the response should ALWAYS be in UTC format. At the below query, when the data is read it will be converted to the client’s timezone. I don’t want TIME_COLUMN to be converted to any time zone. It should remain in the UTC time zone. How can I define TIME_COLUMN in that way?

Notes: I cannot edit the DB timezone. I cannot edit select queries using At time zone.

"TIME_COLUMN" TIMESTAMPTZ default (now() at time zone 'utc'),

Advertisement

Answer

You could set the timezone of your RDBMS to UTC, see https://medium.com/building-the-system/how-to-store-dates-and-times-in-postgresql-269bda8d6403

When that’s done, whatever dates you store, they will be in UTC. Converting from UTC into something else can be done either in queries, like

select created_at at time zone 'utc' at time zone 'america/los_angeles'
from users;

Taken from https://popsql.com/learn-sql/postgresql/how-to-convert-utc-to-local-time-zone-in-postgresql

Or, you can convert the timezone at application level.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement