简体   繁体   English

不带时区的 PostgreSQL 时间戳和带时区的 java.util.Date 之间的比较

[英]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 .在数据库中, publicationDate列的类型为timestamp without time zone Sample value in this column:此列中的示例值:

2018-03-01 18:00:00

The result of now.toString() is: now.toString()的结果是:

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 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 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 .当 PostgreSQL 的 JDBC 驱动程序读取一个timestamp without time zone类型的timestamp without time zonetimestamp without time zone ,它通常可以将它读取到java.sql.Timestampjava.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.如果您选择将其读取到java.util.Date (您的情况),PostgreSQL 的 JDBC 驱动程序会自动将本地 JVM 时区添加到其中。 That makes sense since the whole point of a column of type timestamp without time zone is to be treated as a "local" timestamp.这是有道理的,因为timestamp without time zone类型列的整个点将被视为“本地”时间戳。

Conversely, when you send a java.util.Date to the database it strips down the time zone right away.相反,当您将java.util.Date发送到数据库时,它会立即剥离时区。 Therefore the query condition will take the form:因此查询条件将采用以下形式:

2018-03-01 18:00:00 < 2018-08-22 16:14:03 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.附带地,这意味着建议您显式设置 JVM 时区,以确保 JDBC 驱动程序以正确的方式将timestamp without time zone的数据库timestamp without time zone重新组装到java.util.Date

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.尽管如此,对于使用“本地”时间戳的应用程序来说,这可能不是一个有效的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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