I need to extract only the month and year data from the Java date for display in the GUI. This date must be translated using the user locale. I know two ways to format localized dates:
- Using
DateFormat.getInstance(DateFormat.LONG, locale).format(date) - Using
new SimpleDateFormat("yyyy M", locale).format(date)
For the locale SIMPLIFIED_CHINESE and date 2013-02-18 this gives:
We need to use the LONG format without a day (2013 年 2 月). [Option 2 is clearly unacceptable, since the language standard does not affect the order of the year. The problem may be this: how to remove the day part (18 日) from the long format? I tried using the format(Date date, StringBuffer toAppendTo, FieldPosition pos) method format(Date date, StringBuffer toAppendTo, FieldPosition pos) , but this only allows format(Date date, StringBuffer toAppendTo, FieldPosition pos) to extract part of the number, not an extra character.
The sample DateFormat.getInstance(DateFormat.LONG, Locale.SIMPLIFIED_CHINESE) is yyyy'年'M'月'd'日' . Extracting part of the day will give yyyy'年'M'月' . It seems to me that to achieve this it is impossible to use the Java DateFormat standard, since additional characters ( 年 , 月 and 日 ) are not displayed in the corresponding field, but are simply characters without other semantics for the formatter.
I looked at DateFormatSymbols and LocaleServiceProvider , but I think this does not help. For me, the extension point would be to add another date style to the getInstance(int style) method. But this is not possible without its implementation for all Locale ...
Is this analysis correct? How to achieve this formatting in a clean way?
Jidehem
source share