Using GWT’s DateTimeFormat in Server-Side Code

I was working on some utility class to format dates. As the formatting is the same on server and client the same class should be used on both, server and client. Within the GWT framework there is the DateTimeFormat class which seems to be supposed to do exactly that.

But despite being in the shared package (com.google.gwt.i18n.shared.DateTimeFormat) using it in the server-side code causes

java.lang.UnsupportedOperationException: ERROR: GWT.create() is only usable in client code!  It cannot be called, for example, from server code. If you are running a unit test, check that your test case extends GWTTestCase and that GWT.create() is not called from within an initializer or constructor.

Having a look into the code of the DateTimeFormat class (which is part of the shared package of the GWT framework, thus can be used on server and client) reveals there is an import of com.google.gwt.i18n.client.LocaleInfo. But this class is part of the client package – thus, it can not be used in the server-side code. It’s unclear to me why this was done like that because it simply can not work by definition…

Going down a bit further in the code of the DateTimeFormat class shows that the client package class LocaleInfo is used only once like this:

private static DateTimeFormatInfo getDefaultDateTimeFormatInfo() {
  // MUSTFIX(jat): implement
  return LocaleInfo.getCurrentLocale().getDateTimeFormatInfo();
}

The line is marked as “MUSTFIX” but for some reason it has not been fixed yet.
There is a way to fix this issue that worked for me:

  • Copy the content of DateTimeFormat to a new file in your own code
  • Remove the import of LocaleInfo
  • Changing the following method (starting in line 656) like this:
private static DateTimeFormatInfo getDefaultDateTimeFormatInfo() {
  return new DefaultDateTimeFormatInfo();
}
  • And use this newly created class from now on in all your code.

The fix does not seem to cause any major harm, but as John A. Tamplin (cf. his comment below) clearly pointed out, applying this fix will render all dates using the default locale instead of using the user’s locale. Thus, this fix should be considered a hack rather than a patch – but it does the trick until the bug has been fixed officially.

The hack can be applied quickly – or simply download the fixed class here.

p.s. Unfortunately, it is not possible to just overwrite the method in a derived class because it’s a static method and private anyway.
p.p.s. As suggested in the comments, you might also initialize the DateTimeFormat with a new DefaultDateTimeFormatInfo() as the second paramenter. (Please note that I did not verify this suggestion) In general, both ways of fixing this issue will cause that the date and time to be formated using the default locale rather than the user’s current locale, unfortunately.