我們有一個用戶上傳數據庫數據的場景。用戶從數據庫中讀取數據到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
不清楚問題出在序列化還是數據庫中,而且您還沒有給我們任何代碼或任何涉及類型的跡象。這使得很難給出答案。 –
只是猜測:保存日期爲毫秒(類型爲Long)? –