How to extract date fields for local formatting in Java?

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:

  • 2013 年 2 月 18 日
  • 2013 2

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?

+7
source share
1 answer

I do not think that any predefined constants would exist for formatting the year and month in the zh-CN locale, so you need to format it.

  new SimpleDateFormat("yyyy年M月").format(date) 

As SimpleDateFormat says (highlighted by me):

Date and time formats are indicated by strings of date and time patterns. In strings of a date and time sequence, unquoted letters from "A" to "Z" and from "a" to "z" are interpreted as pattern letters representing the components of a date or time string. Text can be specified using single quotation marks (') to avoid interpretation. "" represents one quote. All other characters are not interpreted ; they are simply copied to the output line during formatting, or matched to the input line during parsing.

Thus, it is safe to put Chinese characters in the format string this way.

Since Java is Unicode, you can embed characters in your source as long as you compile it using the Unicode character set. Otherwise, you should read this line from the outside, for example. from some file or Unicode database.

+1
source

All Articles