简体   繁体   中英

DateFormat with Country Locales issue

I'm writing a multilingual Program and I have set my Locales to Country specific ones (eg de_AT, de_DE,en_US,en_GB). So if I call DateFormat.getDateInstance(int fomat,Locale l) I get always the English one! It works if I use language only Locales (eg En, de,...)

I have reviewed the Oracle Doc of DateFormat , but also with their examples the Error occurs.

Here is an example Program:

import java.text.DateFormat;
import java.util.Locale;
import java.util.Date;

public class DateFormatTest {
  public static void main(String args[]){
    Locale[] locales={new Locale("de_AT"),new Locale("de_DE"), new Locale("de"), new Locale("en_US"), new Locale("en"), new Locale("fr_FR"), new Locale("fr_CA"), new Locale("fr")};
    Date today= new Date();
    for(Locale l: locales){
        System.out.println(l.toString()+"\t"+
              DateFormat.getDateInstance(DateFormat.DEFAULT,l).format(today)+"\t"+
              DateFormat.getDateInstance(DateFormat.FULL,l).format(today));
    }
  }
}

This is the output:

huwa@hubefl-ws:~/tmp$ javac DateFormatTest.java 
huwa@hubefl-ws:~/tmp$ java DateFormatTest 
de_at   Nov 8, 2011 Tuesday, November 8, 2011
de_de   Nov 8, 2011 Tuesday, November 8, 2011
de      08.11.2011  Dienstag, 8. November 2011
en_us   Nov 8, 2011 Tuesday, November 8, 2011
en      Nov 8, 2011 Tuesday, November 8, 2011
fr_fr   Nov 8, 2011 Tuesday, November 8, 2011
fr_ca   Nov 8, 2011 Tuesday, November 8, 2011
fr      8 nov. 2011 mardi 8 novembre 2011

Has anybody the same problem? Is there a solution?

According to the javadocs , the constructors are

Locale(String language)
Locale(String language, String country)
Locale(String language, String country, String variant)

so when you are creating new Locale("de_AT") , it tries to use language "de_AT" which does not exist, so it falls back to the default (English).

Try

Locale[] locales={new Locale("de", "AT"), new Locale("de", "DE"), ...};

The problem is the way you're constructing the Locale objects. Pass the country and language as separate arguments, eg

Locale[] locales = { new Locale("de", "AT"), new Locale("de", "DE"), 
    new Locale("de"), new Locale("en", "US"), new Locale("en"), 
    new Locale("fr", "FR"), new Locale("fr", "CA"), new Locale("fr")};

尝试

DateFormat.getDateInstance(DateFormat.FULL,Locale.GERMANY).format(today));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM