How to get UTC timestamps from JDBC+postgreSql timestamp?

前端 未结 3 1431
别那么骄傲
别那么骄傲 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:47

    The solution proposed by Pavel (adding the jvm param '-Duser.timezone=UTC') is for sure the best option, if you don't have system access, this isn't always possible to do.

    The only way I found is to convert the timestamp to epoch in the query and read it as a long.

    SELECT  extract(epoch from my_timestamp_colum at time zone 'utc')::bigint * 1000 
                AS my_timestamp_as_epoc
    FROM    my_table
    

    Then read it in plain JDBC with

    ResultSet rs = ...
    long myTimestampAsEpoc = rs.getLong("my_timestamp_as_epoc");
    Date myTimestamp = new Date(myTimestampAsEpoc);
    

    With iBatis/MyBatis, you need to handle the column as a Long, then convert it manually to Date/Timestamp. Inconvenient and ugly.

    The reverse operation in PostgreSQL can be done with:

    SELECT TIMESTAMP WITHOUT TIME ZONE 'epoch' + 
           1421855729000 * INTERVAL '1 millisecond'
    

    That said, the JDBC specification doesn't say that the returned timestamp shall or shall not shift the timestamp to the user time zone; BUT since you defined the table column as 'timestamp without time zone' I would expect no time shifts, but the recorded epoch being just wrapped in a java.sql.Timestamp. For my opinion, this is a bug in the PostgreSQL JDBC driver. Being the problem at this level, then, probably there is not much more that can be done, without system access.

提交回复
热议问题