2011-12-07 48 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。在显示时间时,我只会将其更改为用户的首选时区。这避免混淆了哪个时区用于存储或检索日期/时间,是否正确等。