Florent.M Florent.M - 8 months ago 84
Java Question

dates change between client and server side (GWT)

I have a problem that I can't understand. I tried to find the answer a lot of time, but without success.

I work with GWT client side, and Java server side.

Client side, I read dates (java.util.date). And when I send these dates to server side, there sometimes is an hour offset when I receive it.
I know there are many problems with TimeZone. But I think TimeZone aren't responsible of my problem, because not all dates are wrong. To test which dates were wrong, I create a method which create a List of all dates between 1st January of 1900 and today, and which send this list to the server.

When I read the list received in server, here are the results :

  • All dates are correct from the year 1995 (dates didn't change during sending)

  • From 1979 to 1995 (approximately): All dates are correct, except 28 days in september / october (from the swith to winter daylight saving time). It's incorrect because of an offset of one hour.

  • Before : some dates are correct, and some incorrect.

So I tried to add 100 years to my dates client side, send it and remove 100 years server side. And all received dates were correct !

Anybody already had this problem ? And anybody understood this problem ? Any help is welcome.

Thanks !

Edit :

Ok I solved the problem. Read answer of Andrei Volgin to understand the problem. And here is the code which solved it :

// Create date you want
Date date = new Date()

// Get TimeZone of your date
TimeZone timeZone = TimeZone.createTimeZone(date.getTimezoneOffset());

// Adapt your date with the TimeZone
date.setTime(date.getTime() - (timeZone.getOffset(date) * 60000));

// You can send your date to server
// TimeZone server side is "UTC", and all dates received are correct


This is a TimeZone problem.

TimeZone definitions and especially daylight savings rules have changed over the years. If you simply pass the time zone ID or create a time zone using an offset, the browser is unaware of these changes. So the browser simply uses the time-zone offset and current DST setting for this time zone when displaying time. Most of the time this results in a correct time, but not always. This also explains why all dates in the future are correct.

In order to get the accurate conversion, you need to create a TimeZone object using a JSON data string that GWT provides, i.e. use createTimeZone(java.lang.String tzJSON) or createTimeZone(TimeZoneInfo timezoneData).