如何让 PostgreSQL 将所有 java.sql.Timestamp 视为 UTC "zone"?

How make PostgreSQL consider all java.sql.Timestamp as being in the UTC "zone"?

我希望 PostgreSQL 始终采用 UTC。这很好用:我像这样将 java.sql.Timestamp 插入 PostgreSQL:

insert into posts(created_at, ...) values (? at time zone 'UTC', ...)

但是如果我删除 "at time zone 'UTC'",PostgreSQL 会以某种方式将时间戳转换为我的本地时区。恐怕有时我会在插入或更新时间戳时忘记附加 "at time zone 'UTC'"。有没有办法让 PostgreSQL 自动将所有时间戳处理为 UTC 时间?所以我可以在任何地方删除 "at time zone 'UTC'"

created_at 是一个 timestamp without time zone。不确定这个设置是否重要:(它已经是 UTC,至少当我通过 psql 测试时)

SELECT  current_setting('TIMEZONE');
current_setting 
-----------------
UTC

这似乎可行:保存 java.sql.Timestamp 时指定 UTC 日历:

thePreparedStatement.setTimestamp(bindPosition, timestamp, calendarUtcTimeZone)

其中 calendarUtcTimeZone 是:

def calendarUtcTimeZone = ju.Calendar.getInstance(UtcTimeZone, DefaultLocale)
private val UtcTimeZone = ju.TimeZone.getTimeZone("UTC")
private val DefaultLocale = ju.Locale.getDefault(ju.Locale.Category.FORMAT)

加载时间戳并将其转换为 java.util.Date 时也需要日历:

  def getDate(rs: js.ResultSet, column: String): ju.Date = {
    val timestamp = rs.getTimestamp(column, calendarUtcTimeZone)
    if (timestamp eq null) null: ju.Date
    else new ju.Date(timestamp.getTime)
  }

现在我可以删除所有 at timestamp 'UTC' — 至少我现在这么认为。

这是关于 setTimestamp 的 Javadoc:

 * With a
 *  <code>Calendar</code> object, the driver can calculate the timestamp
 * taking into account a custom timezone.  If no
 * <code>Calendar</code> object is specified, the driver uses the default
 * timezone, which is that of the virtual machine running the application.