michael nesterenko
michael nesterenko

Reputation: 14439

calendar serialization deserialization

When I serialize date on one pc1 and deserialize it on another pc2 I get local date of pc2. What will I get when do the same with Calendar instance? Will situation will be same or not?

Upvotes: 1

Views: 5756

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Date represents a point in time (number of milliseconds from 1st of January 1970). Do not be confused by the time zone in Date.toString(), you are always serializing long value wrapped in a class.

Calendar on the other hand represents date and time in given time zone. This means that if the source computer is in GMT+1 and the target one in the GMT+2, but you are sending Calendar set to GMT-6, it will be GMT-6 all the way on both sides.

That being said it is much safer (and uses less bandwidth) to send Date and let every computer display it using local time zone.

Upvotes: 5

qrtt1
qrtt1

Reputation: 7957

The Calendar class implements the Serializable, you can use serialization api to save it. However, I like the timestamp:

The currently set time for this calendar, expressed in milliseconds after January 1, 1970, 0:00:00 GMT.

We can deserialize timestamp by new Date(timestamp) simply, it will convert to local timezone automatically.

Calendar class also defines the setTime method:

Calendar.getInstance().setTime(date)

or

Calendar.getInstance().setTimeInMillis(ts)

Upvotes: 2

Related Questions