Reputation: 1654
I'm using
DateFormat format = new SimpleDateFormat("MMM yyyy", locale);
String dateStr = format.format(date);
But I get back an incorrect translation in some languages: it's missing the 年 character in years. I'll get 7月 2014 instead of 7月 2014年.
Is there any way to get the 年 or any recommended workaround?
Upvotes: 2
Views: 4556
Reputation: 5787
You should use DateFormat with a "MMMy" skeleton, and that will give you a pattern that is good to use for formatting.
Something like this:
String pattern = DateFormat.getBestDateTimePattern(locale, "MMMy");
DateFormat format = new SimpleDateFormat(pattern, locale);
String dateStr = format.format(date);
In skeletons the order or spaces in the fields don't matter, they are there just to tell "I want a year-month format, with abbreviated month name, appropriate for that locale"
It is better to have the year as a single "y", otherwise all years will be zero-padded to 4 digits. Right now this is not a problem, but if Android gets to support alternate calendars it might become a problem (for instance a date in the Japanese imperial calendar will show as "平成0015年1月", not good :-)
Mihai
Upvotes: 2
Reputation: 18662
You got back exactly what you asked for. If you want to have year reference in your pattern, you need to add it. So the solution to your problem could be as simple as:
DateFormat format = new SimpleDateFormat("M'月' yyyy'年'", locale);
There are two issues here, though. First, the date format:
DateFormat shrtDate = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA);
String pattern = ((SimpleDateFormat) shrtDate).toPattern();
This reveals (on regular Java, which is usually more reliable):
yyyy'年'M'月'd'日'
In other words, your code should be more like:
DateFormat format = new SimpleDateFormat("yyyy'年'M'月'", locale);
However, this would require externalizing the patterns to each language individually (believe it or not but formats differ) effectively tightening up formatting to User Interface translations. This is bad.
There is a solution to your problem, if you can use ICU instead. ICU's DateFormat contains the pattern you want to use and you can get it for various locales:
DateFormat format = DateFormat.getPatternInstance(DateFormat.YEAR_MONTH, locale);
Just to let you know, some people claimed that ICU is slow on Android. I haven't tested it myself, so I can't tell you whether it's true or not, but it would resolve your specific problem correctly.
Upvotes: 7