2014-11-14 17 views
0

用戶在我的Web應用程序的頁面上選擇日期和時間(如果有問題,請使用Grails)。我知道用戶的時區(他們在用戶首選項中設置它)。我現在要將該日期保存爲數據庫,如UTC(使用Hibernate,如果這很重要)。將日期保存爲數據庫爲UTC

所以,這裏是我的域類:

class Even { 
    Date startTime 
} 

我有點想,我想這樣做:

def beforeInsert() { 
    startTime = new DateTime(startTime, user.timeZone).withZone(TimeDateZone.UTC).toDate() 
} 

toDate()在剛剛結束返回相同startTime與我開始(因爲日期沒有我認爲的時區信息)。

那麼,如何獲得用戶提供的Date(考慮到他們的時區)並將其作爲UTC持久保存到數據庫?

我正在考慮做類似new Date() - user.timeZone.rawOffset的事情,但後來我不得不處理夏令時節省,而且感覺非常容易出錯。

+0

看看這個:http://stackoverflow.com/questions/11294307/convert-java-date-to-utc-string – MihaiC

+0

http://stackoverflow.com/questions/12208305/grails-saves-datetime -as-UTC時間,但是,讀入它,作爲本地服務器時間 – user1690588

回答

0

可能有一個更快的解決方案,但這樣做的標準方式是自定義休眠UserType。下面是一個處理Hibernate 3.x部件的示例實現(接口在4.x中略有不同,但代碼將幾乎相同),並將字符串 - >日期和日期 - >字符串轉換爲讀者的練習:

package my.package 

import java.sql.PreparedStatement 
import java.sql.ResultSet 
import java.sql.SQLException 
import java.sql.Types 

import org.hibernate.usertype.UserType 

class UtcDateUserType implements UserType { 

    def nullSafeGet(ResultSet rs, String[] names, owner) throws SQLException { 
     String value = rs.getString(names[0]) 
     if (value) { 
      return utcStringToDate(value) 
     } 
    } 

    void nullSafeSet(PreparedStatement st, value, int index) throws SQLException { 
     if (value) { 
      st.setString index, dateToUtcString(value) 
     } 
     else { 
      st.setNull index, Types.VARCHAR 
     } 
    } 

    protected Date utcStringToDate(String s) { 
     // TODO 
    } 

    protected String dateToUtcString(Date d) { 
     // TODO 
    } 

    def assemble(Serializable cached, owner) { cached.toString() } 
    def deepCopy(value) { value.toString() } 
    Serializable disassemble(value) { value.toString() } 
    boolean equals(x, y) { x == y } 
    int hashCode(x) { x.hashCode() } 
    boolean isMutable() { false } 
    def replace(original, target, owner) { original } 
    Class<String> returnedClass() { String } 
    int[] sqlTypes() { [Types.VARCHAR] as int[] } 
} 

將其註冊到mapping塊的域類中,例如

import my.package.UtcDateUserType 

.... 

static mapping = { 
    startTime type: UtcDateUserType 
} 

這被描述爲in the docs here

相關問題