6

I am trying to display a (java.util.)Date client-side, and it keeps using the browser's timezone, resulting in a different date visible depending on where you view the page.

How do I get the Formatter (DateTimeFormat) to display the date using the server's timezone rather than the user?

Thanks

2 Answers 2

3

The "easiest" solution (one that doesn't require any communication with the server) is just forcing DateTimeFormat to use a particular timezone (the one your server is in), like this:

String pseudoServerTime = DateTimeFormat.getFullTimeFormat().format(new Date(), TimeZone.createTimeZone(TimeZoneConstants.europeWarsaw());

You can hardcode the timezone string/object somewhere as public static final so that it can be easily changed, if you move/change servers (and the GWT compiler will inline this, so no performance penalty).

2
  • Thanks Igro - that was my first guess, although I had just hardcoded the timezone offset. My problem with using the hardcoded offset is that we are currently in daylight savings time here (Sydney, Australia) and when that ends the time will be out again.
    – RodeoClown
    Feb 3, 2010 at 4:59
  • 1
    Don't hardcode the offset. Hardcode the TimeZone object and the daylight savings will be taken into account. Aug 10, 2012 at 14:47
1

Will the date be modified on the client? If not do the format on the server and just send over a string value. One last thing. There seems to be some issues with Dates on the client side in GWT. Refer to http://blog.gerardin.info/archives/674

3
  • Hi Carnell, the date won't be modified on the client, but it is used in a table for sorting, and is being formatted as "31st of January 2010", so making it a string server-side would prevent the sorting from working. Checking out the link now. Thanks
    – RodeoClown
    Feb 3, 2010 at 23:46
  • You can pass the Date as a String for display and also pass the numerical value of the Date to use for sorting. Use Date.getTime() to get the long value for the Date. The only thing that sucks about this is that you have to pass another field to the client but it should work.
    – Carnell
    Feb 4, 2010 at 23:51
  • Couldn't you just pass the String from the server (using java's SimpleDateFormat) with the Locale set, eg: yyyy-MM-dd hh:mm Z, and using this format on the client, creating a date using the DateTimeFormater of GWT. You'd be creating a date with the timezone from the server, and could also use it for other purposes. May 9, 2012 at 7:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.