expert
expert

Reputation: 30135

How can I shift timezone of Date object created in local timezone to target timezone in GWT client?

How can I shift timezone of Date object created in local timezone to target timezone?

Here is what I need. I want web-client to pick a date using DatePicker but resulting Date object should look like as if it was picked in another timezone. Since there is no way to tell DatePicker to do that I have to manually shift date.

For example it's Apr 6th 2012 2:42AM in California right now. Created Date will be in UTC-7 timezone. I want to have Date object with Apr 6th 2012 2:42AM in Europe/Moscow timezone.

Here is I do it right now:

final TimeZoneConstants constTz = GWT.create(TimeZoneConstants.class);
final TimeZone timeZoneMsk = TimeZone.createTimeZone(constTz.europeMoscow());
final TimeZone timeZoneCali = TimeZone.createTimeZone(constTz.americaLosAngeles());

Date curTime = new Date();

DateTimeFormat dateTimeFormat = DateTimeFormat.getFullDateTimeFormat();
Date mskTime = new Date(curTime.getTime() - (curTime.getTimezoneOffset() - timeZoneMsk.getStandardOffset()) * 60 * 1000);

String strLocal = dateTimeFormat.format(curTime, timeZoneCali); // Friday, 2012 April 06 02:42:59 Pacific Daylight Time
String strMsk = dateTimeFormat.format(mskTime, timeZoneMsk);    // Friday, 2012 April 06 02:42:59 Moscow Standard Time

There are two problems with this method:

Or should I just produce string with full date of local Californian time, replace timezone in string and then generate new Date by calling DateTimeFormat.parse() ? It looks pretty hacky too...

Also what do you think of JodaTime for GWT ? Is it stable enough for production ?

Upvotes: 1

Views: 600

Answers (1)

Joni
Joni

Reputation: 111269

Your code looks about right. Using DateTimeFormat.parse might make the intention clearer to a casual reader. It's not very often that you are given timezones A and B and one Date object, and you have to produce a new Date object that, when formatted in B, has the same time as the original when formatted in A.

Timezone in mskTime is still -0007. I wonder if it can cause any problems in future when I deserialize this object from Google App Engine datastore.

No, there can be no problems. Remember that a Date object represents a universal point in time not bound to a timezone. When it's April 6 14:40 in Moscow, it's April 6 03:40 in California, so the Date objects are equal.

Upvotes: 1

Related Questions