簡體   English   中英

如何讓PostgreSQL將所有java.sql.Timestamp都視為位於UTC“區域”中?

[英]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', ...)

但是,如果我刪除“在時區'UTC'” ,PostgreSQL會以某種方式將時間戳轉換為我的本地時區。 恐怕有時在插入或更新時間戳時,我會忘記附加“在時區'UTC'” 有沒有辦法讓PostgreSQL自動將所有時間戳作為UTC時間處理? 因此,我可以任何地方刪除“在時區'UTC'”

created_attimestamp without time zonetimestamp without time zone 不知道此設置是否重要:(至少在我通過psql測試時,它已經是UTC了)

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM