简体   繁体   中英

Comparsion between PostgreSQL timestamp without timezone and java.util.Date with timezone

I would like to know how the comparsion in the following query will be performed:

StringBuilder queryStr = new StringBuilder();
queryStr.append("SELECT o FROM PRDBook as o WHERE ")
        .append("o.publicationDate < :now");

Query query = entityManager.createQuery(queryStr.toString());
Date now = new Date();
query.setParameter("now", now);

In the database, column publicationDate has type timestamp without time zone . Sample value in this column:

2018-03-01 18:00:00

The result of now.toString() is:

Wed Aug 22 16:14:03 CEST 2018

Will the comparsion between mentioned data be performed in that way:

2018-03-01 18:00:00 < 2018-08-22 16:14:03

or that way:

2018-03-01 18:00:00 < 2018-08-22 14:14:03

Interesting question.

When PostgreSQL's JDBC driver reads a column of type timestamp without time zone , it can usually read it to a java.sql.Timestamp or java.util.Date .

If you choose to read it to a java.util.Date (your case) PostgreSQL's JDBC driver automatically adds the local JVM time zone to it. That makes sense since the whole point of a column of type timestamp without time zone is to be treated as a "local" timestamp.

Conversely, when you send a java.util.Date to the database it strips down the time zone right away. Therefore the query condition will take the form:

2018-03-01 18:00:00 < 2018-08-22 16:14:03

Collaterally, this means it's recommended you set the JVM time zone explicitly , to make sure the JDBC driver is reassembling the database timestamp without time zone into a java.util.Date the correct way.

Otherwise, different servers in different time zones reading the same row in the same database will interpret that timestamp as a different moment in time. Nevertheless, this should probably not be a valid use case for an application that uses "local" timestamps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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