java - 如何从JDBC+postgreSql时间戳获取UTC时间戳?

标签 java postgresql datetime jdbc

我在 PostgreSQL 中创建了一个这样的表:

create table myTable (
    dateAdded timestamp(0) without time zone null default (current_timestamp at time zone 'UTC');
)

我选择“无时区”是因为我知道我的应用程序使用的所有时间戳都是始终 UTC。就我得到的文档而言,与“带时间戳”的唯一区别是我可以提供其他时区的值,然后将这些值转换为 UTC。但是我想避免这种自动转换,因为如果我知道我的值是 UTC,它们几乎不会有任何好处。

当我在我的测试表中添加一条新记录并使用 pgAdmin 查看该表的内容时,我可以看到插入日期已正确保存为 UTC 格式。

但是,当我尝试使用 JDBC 选择值时,该值会减去 2 小时。我位于 UTC+2,所以看起来 JDBC 假定表中的日期不是 UTC 时间戳,而是 UTC+2 时间戳,并尝试转换为 UTC。

一些谷歌搜索显示,JDBC 标准规定了一些关于与当前时区之间的转换,但这可以通过为 getTimestamp/setTimestamp 调用提供日历来防止。然而,提供日历根本没有任何区别。这是我的 MyBatis/Jodatime 转换器:

@MappedTypes(DateTime.class)
public class DateTimeTypeHandler extends BaseTypeHandler<DateTime> {
    private static final Calendar UTC_CALENDAR = Calendar.getInstance(DateTimeZone.UTC.toTimeZone());

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i,
            DateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, new Timestamp(parameter.getMillis()), UTC_CALENDAR);
    }

    @Override
    public DateTime getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return fromSQLTimestamp(rs.getTimestamp(columnName, UTC_CALENDAR));
    }
    /* further get methods with pretty much same content as above */

    private static DateTime fromSQLTimestamp(final Timestamp ts) {
        if (ts == null) {
            return null;
        }
        return new DateTime(ts.getTime(), DateTimeZone.UTC);
    }
}

从JDBC+PostgreSQL时间戳源获取UTC时间戳的正确方法是什么?

最佳答案

解决方案

将 UTC 设置为 JVM 的默认时区 -Duser.timezone=UTC 或将整个操作系统设置为 UTC。

背景

在 Postgres 中,TIMESTAMPTIMESTAMP WITH TIMEZONE 的存储方式相同 - 自 Postgres 纪元 (2000-01-01) 以来的秒数。主要区别在于 Postgres 在保存诸如 2004-10-19 10:23:54+02 之类的时间戳值时执行的操作:

  • 没有 TZ,+02 就被剥离了
  • 使用 TZ 执行 -02 校正以使其成为 UTC

现在有趣的是 JDBC 驱动程序何时加载值:

  • 在没有 TZ 的情况下,存储的值由用户的(JVM/OS)TZ 移动
  • 对于 TZ,该值被认为是 UTC

在这两种情况下,您最终都会得到带有用户默认 TZ 的 java.sql.Timestamp 对象。

时区

没有 TZ 的时间戳非常有限。如果您有两个系统连接到您的数据库,都具有不同的 TZ,它们将以不同的方式解释时间戳。因此,我强烈建议您使用 TIMESTAMP WITH TIMEZONE


更新

您可以 tell JDBC通过 ResultSet#getTimestamp(String, Calendar) 读取时间戳时应该使用哪种 TZ .摘自 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.

关于java - 如何从JDBC+postgreSql时间戳获取UTC时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26064489/

相关文章:

java - 从属性文件更新 Spring @Scheduled Cron

java - 通过迭代 1000 行的映射来对每 10 个值运行一次批量更新

PHP:与下个月相关的日期函数结果不正确(PHP 错误或 sg.else?)

python-2.7 - 如何更改Python中的日期格式

SQLite 日期时间与 ISO8601 中的 'now' 的比较

java - 如何从对象 id 的 String[] 中保存 List<ParseUser>

java - 更改所有 Activity 的背景颜色

POSTGRESQL - 返回选择查询时出错

java - 如何使用 Java/Vaadin 查询 PostgreSQL View ?

postgresql - RDS 快照恢复时间过长