I need to extract only the month and year information from a Java Date to display in a GUI. This date must be translated using the user locale. I know 2 ways for formatting localized dates:
- Using
DateFormat.getInstance(DateFormat.LONG, locale).format(date)
- Using
new SimpleDateFormat("yyyy M", locale).format(date)
For locale SIMPLIFIED_CHINESE
and date 2013-02-18
, this gives:
- 2013年2月18日
- 2013 2
We need to use the LONG
format without day (2013年2月). [The variant 2 is clearly not acceptable since the ordering of year-month is not affected by the locale].
The problem could be: how to remove the day part (18日) from the long format ?
I tried using the method format(Date date, StringBuffer toAppendTo, FieldPosition pos)
, but this allows only extracting the number part, not the extra character.
The pattern of the DateFormat.getInstance(DateFormat.LONG, Locale.SIMPLIFIED_CHINESE)
is yyyy'年'M'月'd'日'
. Extracting the day part would yield yyyy'年'M'月'
.
It seems to me that it's not possible to use Java's DateFormat standard to achieve this since the extra characters (年
, 月
and 日
) do not seem mapped to the corresponding field, but are simply characters without other semantic for the formatter.
I had a look to DateFormatSymbols
and LocaleServiceProvider
, but think it doesn't help.
To me, the point of extension would be adding another date style to the getInstance(int style)
method. But it doesn't seem possible without implementing it for all the Locale...
Is this analysis correct ? How to achieve this formatting in a clean way ?
YearMonth.fromCalendarFields(cal).toString(DateTimeFormat.longDate().withLocale(locale))
. – Turntable