我在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时间戳?