Question

I'm using GWT RPC to send a string containing a date from the client to the server (it has to be this way, because it's on a request header).

On the server side I parse that string with SimpleDateFormat and make the logic I want.

I'm setting both my cell phone and computer to different time zones, and will use hosted mode and running the test project on tom cat.

Here's the code:

Client:

DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss Z");
Date date = new Date();

System.out.println("client: " + date.toString());
System.out.println("client: " + dtf.format(date));
builder.setHeader("Date1", dtf.format(date));

Server:

String dateHeader = request.getHeader("Date1");
System.out.println("Server date header from client: " + dateHeader);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");

System.out.println("x = " + sdf.parse(dateHeader));
System.out.println("Timezone = " + df.getTimeZone().getDisplayName());

Result:

Hosted Mode
client: Wed Apr 11 17:29:49 NOVST 2012
client: 2012-04-11 17:29:49 +0700
Server date header from client: 2012-04-11 17:29:49 +0700
x = Wed Apr 11 17:29:49 NOVST 2012


TomCat

  1. Using PC: Client, and server have the same time.

(Can't see the print of the client, obviously)

Server date header from client: 2012-04-11 17:31:37 +0700
x = Wed Apr 11 17:31:37 NOVST 2012

  1. Cellphone client, has a different from the server.

Server date header from client: 2012-04-11 15:34:35 +0500
x = Wed Apr 11 17:34:35 NOVST 2012

Conclusion: SimpleDateFormat ignores the Timezone that comes on the string. I don't want that! I want this to work properly. How can I make this work? Thank you in advanced.

Was it helpful?

Solution

SimpleDateFormat doesn't ignore the timezone, as it has adjusted the time, parsing 15:34:35 +0500 into 17:34:35 NOVST (where NOVST is +0700, the local timezone), it's just that java.util.Date is only a timestamp from Epoch and has no notion of a timezone (see the javadoc: everything is relative to the local timezone).

If you want to get the timezone of the client on the server-side, you'll have to parse the timezone field out of the serialized date (you could split on spaces, keep the last part –the timezone part– and pass it to java.util.TimeZone.getTimeZone() prefixed with GMT).
Alternatively, you can use JodaTime whose DateTime type keeps track of the timezone info; something like:

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss Z");

DateTime dt = fmt.parseDateTime(dateHeader);
System.out.println("x = " + fmt.print(dt));
System.out.println("Timezone = " + dt.getZone().toTimeZone().getDisplayName());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top