I have a Date object being serialized from a server to a client (located in two different timezones) and I noticed that the date gets auto-adjusted to reflect the local timezone. There are places in the client app where this is desired; however, there are places where I need to keep the date based on the server's timezone. Basically, I don't want certain date objects to auto-adjust.
I noticed that you can set the client's timezone to the server's by calling this: TimeZone.setDefault(serverTimeZone);
The problem with this approach is that it globally applies this for all Date objects and I only need it applied for a select few. Is there a easy way around this? Do I need to create a subclass of Date or is there something I'm overlooking?
A java.util.Date object represents an instance in time, and doesn't have a time zone as part of its state. When you print one/convert it to String:
The toString method implicitly uses the JVM's default timezone, and that is why you are noticing dates "change" when sent from machine to machine. (There's a lot a dissing one could do to Date, but it is enough to notice its many deprecated methods...)
One thing you could do is send both a date and a time zone. Note that if you are using a DateFormat to format dates, you may want to set the time zone:
You can also serialize a java.util.Calendar object, and it will come with its timezone state (either the server's default or a time zone you've explicitly set with Calendar's setTimeZone method). Just recall that you still have to transfer the time zome from the Calendar to the DateFormat for it to be used:
As you can tell, I've had a few run-ins with Date, TimeZone, Calendar and DateFormat, and I know how error-prone code can be that uses them, until programmers understand the way these classes depend on each other and what these four can, and can't, do... [ November 18, 2005: Message edited by: Jeff Albrechtsen ]
There is no emoticon for what I am feeling!
Joined: Nov 18, 2005
Thanks so much for the info. Setting the TimeZone on the formatter did the trick!