Search code examples
javalocale

Java date format locale problems with multiples locales


I'm having trouble with a complex corporate web application which has been deployed in a French branch and now has to be deployed also in a German branch of the company. The problem has to do with the different behaviour of DateFormat based on the locale of the server:

The Date for United States:
  In FULL is Tuesday, January 16, 2007
  In LONG is January 16, 2007
  In MEDIUM is Jan 16, 2007
  In SHORT is 1/16/07
The Date for United Kingdom:
  In FULL is 16 January 2007
  In LONG is 16 January 2007
  In MEDIUM is 16-Jan-2007
  In SHORT is 16/01/07
The Date for Germany:
  In FULL is Dienstag, 16. Januar 2007
  In LONG is 16. Januar 2007
  In MEDIUM is 16.01.2007
  In SHORT is 16.01.07
The Date for France:
  In FULL is mardi 16 janvier 2007
  In LONG is 16 janvier 2007
  In MEDIUM is 16 janv. 2007
  In SHORT is 16/01/07

Now the application makes extensive use of:

 brch.setDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("02/04/2013"));

the above seems to work in France and the UK, however when it is deployed in Germany all hell breaks loose and we receive tons of errors. Now I know we can specify the Locale with a

 DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK)

however changing the code for the whole application would require days and a lot of testing, is there a way to specify globally the default locale for this application? Or some way to make the applicaion Locale-agnostic without changing too much the application?

Thank you


Solution

  • is there a way to specify globally the default locale for this application?

    You could call Locale.setDefault at the start of the program, to force the default locale for everything that uses it - including DateFormat.getDateInstance.

    However, I would strongly advise you to refactor the code anyway. All you've got to do is change every code which currently uses DateFormat.getDateInstance to call a utility method which is under your control. You can then easily change the behaviour in one place centrally, as your requirements change. Even just a plain search and replace would probably allow you to extract this to a static method in a controlled class fairly easily, as a first step.

    Yes, this will take a bit of time - but you'll be much better off after it.

    Personally, I would recommend that if you've actually got a very fixed format, you specify that explicitly - if you know it's always dd/MM/yyyy, I'd use:

    DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
    

    ... and then set the time zone appropriately too. In fact, I'd use Joda Time instead of any of this, but that's a different matter.