How to get UTC timestamps from JDBC+postgreSql timestamp?

前端 未结 3 1419
别那么骄傲
别那么骄傲 2021-02-02 14:06

I created a table like like this in PostgreSQL:

create table myTable (
    dateAdded timestamp(0) without time zone null          


        
3条回答
  •  时光说笑
    2021-02-02 14:56

    Solution

    Set UTC as default timezone of your JVM -Duser.timezone=UTC or set your whole OS to UTC.

    Background

    In Postgres both TIMESTAMP and TIMESTAMP WITH TIMEZONE are stored the same way - number of seconds since Postgres epoch (2000-01-01). The main difference is what Postgres do when it saves timestamp value such as 2004-10-19 10:23:54+02:

    • without TZ the +02 is just stripped away
    • with TZ a -02 correction is performed to make it UTC

    Now the interesting thing is when JDBC driver loads the value:

    • without TZ the stored value is shifted by the user's (JVM / OS) TZ
    • with TZ the value is considered to be UTC

    In both cases you will end up with java.sql.Timestamp object with user's default TZ.

    Time Zones

    Timestamps without TZ are pretty limited. If you have two systems connected to your database, both with different TZ, they will interpret timestamps differently. Therefore, I strongly advice you to use TIMESTAMP WITH TIMEZONE.


    Update

    You can tell JDBC what kind of TZ it should use when reading timestamp via ResultSet#getTimestamp(String, Calendar). Excerpt from JavaDoc:

    This method uses the given calendar to construct an appropriate millisecond value for the timestamp if the underlying database does not store timezone information.

提交回复
热议问题