2011-12-07 30 views
2

我們有一個用戶上傳數據庫數據的場景。用戶從數據庫中讀取數據到java對象上,然後將java對象串行到一個文件中。這個文件然後被上傳到遠程服務器。在遠程服務器上,然後將該文件反序列化並將其放到遠程服務器上的數據庫中。反序列化包含時間戳的對象

當我反序列化時間戳和日期時出現問題。與客戶端系統上的時間戳相比,時間戳是不同的。我們將問題追溯到客戶端系統上錯誤設置的時區。客戶在美國和加拿大太平洋時間(UTC - 8:00),服務器在印度時間(UTC + 5:30)。因此,當數據庫插入數據時,會補償時差。我們更改了客戶端系統上錯誤設置的時區,現在一切都很好。

但是我們沒有控制所有的客戶端系統。如果他們在不同的時區(在他們的系統上設置不正確),那麼我們如何指示服務器不補償和存儲數據。這意味着反序列化應該將數據完全按照用戶發送的數據放入數據庫中。另外,如果我們將服務器移動到不同的時區,那麼所有用戶都會遇到問題。

我們使用Java和數據庫是MySQL的

編輯:下面是一個代碼示例:

public class Test 
{ 
public static void main(String[] args) { 
    try { 
     DBObject db = new DBObject(); 
     db.setTs(new Timestamp(System.currentTimeMillis())); 

    //first save the data on one timezone 
     ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("/Users/Sethu/temp/test.dat")); 
     os.writeObject(db); 
     os.close(); 

    //comment the top portion of saving.. change the timezone and run the code, 
    //you will see a different date appearing in your screen 
     ObjectInputStream is=new ObjectInputStream(new FileInputStream("/Users/Sethu/temp/test.dat")); 
     DBObject dbin=(DBObject)is.readObject(); 
     System.out.println(dbin.getTs()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    } 
    } 

    class DBObject implements Serializable{ 
    private Timestamp ts; 

    public Timestamp getTs() { 
    return ts; 
    } 

    public void setTs(Timestamp ts) { 
    this.ts = ts; 
    } 

    } 

編輯2:爲了將日期轉換回它最初創建的時區,我現在已經改變了發送時間序列的代碼。現在的時區是第一序列化對象和DBOBJECT是第二個。現在使用的序列化時區,我試圖改變resonctructed對象:

System.out.println("Current Timezone="+DateTimeZone.getDefault()); 
DateTimeZone timezone=(DateTimeZone)is.readObject(); 
System.out.println("Timezone of saved object="+timezone); 
DBObject dbin=(DBObject)is.readObject(); 
System.out.println("Date in current timezone="+dbin.getTs()); 

System.out.println("Date time Object in timezone of saved object="+new DateTime(dbin.getTs()).withZone(timezone)); 

//This is where the issue is.. As soon as I do this, I get the date in the current timezone again.. 
System.out.println("Date time exported to date="+new DateTime(dbin.getTs()).withZone(timezone).toDate()); 

當我做到這一點,這是我得到的輸出!

Current Timezone=America/Los_Angeles 
Timezone of saved object=+05:30 
Date in current timezone=Tue Dec 06 23:30:56 PST 2011 
Date time Object in timezone of saved object=2011-12-07T13:00:56.687+05:30 
Date time exported to date=Tue Dec 06 23:30:56 PST 2011 
+1

不清楚問題出在序列化還是數據庫中,而且您還沒有給我們任何代碼或任何涉及類型的跡象。這使得很難給出答案。 –

+0

只是猜測:保存日期爲毫秒(類型爲Long)? –

回答

0

您可以在DBObject添加時區信息以及自TimeZone類是可序列。要獲得當前時區,只需使用Calendar.getInstance().getTimeZone()即可。

+0

我確實嘗試過。我將時區添加爲另一個字段,並在服務器上獲得相同的時區。但是,我如何將它應用於反序列化的時間戳?我正在爲此苦苦掙扎。你能幫我編輯你的答案併發佈一個小的代碼片段嗎? – sethu

1

我會將所有時間戳存儲爲服務器和客戶端上的GMT。在顯示時間時,我只會將其更改爲用戶的首選時區。這避免混淆了哪個時區用於存儲或檢索日期/時間,是否正確等。

相關問題