开发者

How to include just enough locale data with an app to be able to format dates in three locales?

开发者 https://www.devze.com 2023-01-26 19:37 出处:网络
I would like to be able to format java.util.Date objects in a \"long\" English, Spanish, and German date format. By \"long\" I mean the locale-dependent date format that corresponds to the LONG style

I would like to be able to format java.util.Date objects in a "long" English, Spanish, and German date format. By "long" I mean the locale-dependent date format that corresponds to the LONG style pattern constant in java.text.DateFormat:

DateFormat.getDateInstance(DateFormat.LONG, myLocale).format(myDate);

With a standard JRE, I get date strings like:

November 22, 2010
22 de noviembre de 2010
22. November 2010

as expected. On Android 1.5, however, I get:

November 22, 2010
2010 11 22
2010 11 22

Is there a way that I can include just enough locale information with my app to be able to format dates correctly in long English, Spanish, and开发者_StackOverflow German formats using java.text.DateFormat?


First of all, the dates formatting in JRE is known for incorrect behavior for many locales (invalid Polish, Czech and Russian long dates, invalid Polish short date; And this are just examples of what I know for sure). So I wouldn't trust this source of information much.

If you want to implement your own long date formatting logic, here is what I would do:

String spanishDatePattern = "{0,number,00} {1} {2,number,####}";
String spanishLongDateMonthNameNovember = "de noviembre de";

Object[] arguments = { new Integer(date.getDate()),
                       spanishLongDateMonthNameNovember,
                       new Integer(date.getYear()) };
String formattedDate = MessageFormat.format(spanishDatePattern,
                arguments);

In this case you will need 13 messages per language (12 month ~names and 1 pattern). Not that much, I believe.

Of course this was just an example, in reality you would probably need to also add logic to resolve month names (having keys with name ending with month number, i.e. longDateFormatMonthName.0=January?).

0

精彩评论

暂无评论...
验证码 换一张
取 消