如何使PostgreSQL认为所有java.sql.Timestamp都在UTC“区域”?

时间:2015-05-21 01:13:25

标签: postgresql jdbc

我希望PostgreSQL始终采用UTC。这很好用:我将(char= #\a #\a)插入到PostgreSQL中,如下所示:

java.sql.Timestamp

但如果我在时区'UTC'“删除”,PostgreSQL会以某种方式将时间戳转换为我的本地时区。我担心有时候当我插入或更新时间戳时,我会忘记在时区'UTC'“附加”。有没有办法让PostgreSQL自动处理所有时间戳作为UTC时间?所以我可以在任何地方删除“在时区'UTC'”

insert into posts(created_at, ...) values (? at time zone 'UTC', ...) created_at。不确定这个设置是否重要:(已经是UTC了,至少在我通过timestamp without time zone进行测试时)

psql

1 个答案:

答案 0 :(得分:0)

这似乎有效:保存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.