17 April 2007

Free internationalized text in Java

The Locale object is absolutely phenomenal. It packs so much, for so little. If you've ever worked with any internationalized app, you know how hard it can be to get things translated and then figure out how to reference it later. Well, you can get a lot of stuff for free with Java. Take the snippet below for example.








import java.text.*;
import java.util.*;
public class DateInLanguage {

  public static void main (String[] args) {
    Locale[] locales = Locale.getAvailableLocales();
    Date d = new Date();
    for (int x=0; x<locales.length; x++) {
      Locale l = locales[x];
      DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, l);
      String country = l.getDisplayCountry();
      String language = l.getDisplayLanguage();      
      String formattedDate = df.format(d);
      System.out.println(l.toString() "\t"+ country + "\t"+language + "\t"+formattedDate);
    }
  }
}




Now, take a look at the output (trimmed):

ar Arabic 17 أبريل, 2007
iw_IL Israel Hebrew יום שלישי 17 אפריל 2007
ja_JP Japan Japanese 2007年4月17日
ko Korean 2007년 4월 17일 화요일
de_LU Luxembourg German Dienstag, 17. April 2007
el Greek Τρίτη, 17 Απρίλιος 2007
en_IE Ireland English 17 April 2007
en_IN India English Tuesday, 17 April, 2007
mk Macedonian вторник, 17, април 2007
tr_TR Turkey Turkish 17 Nisan 2007 Salı
uk Ukrainian вівторок, 17, квітня 2007
en English Tuesday, April 17, 2007


We just got a huge amount of stuff for free! Check it out:

  • translated, in language names for things like the day and month names

  • separators (commas switch to periods) by Locale

  • Ordering of elements in a Locale sensitive manner



Sure- the Locale object is programmed to do this. It should behave like so. But the translations are there too, and you get them on the house. If you look at Locale closely, you can even use it to get language and country names, in other Locales, thereby allowing you to generate a list of languages, with each language in the language it is in. Really helpful when you want to try and present a language or country selection.

No comments:

Post a Comment