SimpleDateFormat本地化的月份名称

Kel*_*lly 6 java localization simpledateformat

我在整个网站上搜索过,但我认为我有一个稍微不同的问题,在我出现心力衰竭或烧坏计算机之前可以真正做些帮助.

我动态生成月份名称列表(以2011年6月,2011年7月的形式),显然我希望这对区域设置敏感:因此我使用简单的日期格式对象,如下所示:

//the actual locale name is dependent on UI selection
Locale localeObject=new Locale("pl"); 
// intended to return full month name - in local language.
DateFormat dtFormat = new SimpleDateFormat("MMMM yyyy",localeObject);
//this bit just sets up a calendar (used for other bits but here to illustrate the issue
String systemTimeZoneName = "GMT";
TimeZone systemTimeZone=TimeZone.getTimeZone(systemTimeZoneName);
Calendar mCal = new GregorianCalendar(systemTimeZone); //"gmt" time
mCal.getTime(); //current date and time
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

String value=dtFormat.format(mCal.getTime()); 
Run Code Online (Sandbox Code Playgroud)

这个"应该"返回月份名称的本地化版本.在波兰语中,"九月"这个词是"Wrzesień" - 请注意n上的重音.然而我回来的只是"Wrzesie?"

我究竟做错了什么?

感谢所有 - 我现在接受这是一个演示问题 - 但我怎样才能安全地"读取"dtFormat的结果 - 我使用getBytes等在ref下面添加了一些注释 - 这在其他情况下工作,我似乎无法获取对字符串结果的访问权限而不会搞砸它

- 最终编辑; 适用于任何涉及此问题的人

答案是在BalusC的博客上:http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html#DevelopmentEnvironment

基本上DTformat对象返回UTF-8,并在我将其读入字符串时自动转换回系统默认字符集

所以这段代码对我有用

new String(dtFormat.format(mCal.getTime()).getBytes("UTF-8"),"ISO-8859-1");
Run Code Online (Sandbox Code Playgroud)

非常感谢你的帮助

Jon*_*eet 4

你的问题与你无关SimpleDateFormat——你只是对结果做了错误的事情。

您还没有告诉我们您之后要如何处理该字符串 - 如何在 UI 中显示它 - 但这就是问题所在。您可以看到它正在获取本地化的字符串;这只是导致问题的重音字符的显示。如果其中有一个包含相同重音字符的字符串常量,您会看到完全相同的结果。

如果是 Web 应用程序,我建议您检查整个应用程序中使用的所有编码;如果是控制台或 Swing 应用程序,请检查显示字符串的字体。

如果您检查调试器中的字符串,我确信您会看到它具有完全正确的字符 - 这就是它们如何到达用户的方式,这就是问题所在。

  • @BalusC:不,它不会完成(超过208个字符) - 我相信它实际上会提供OP问题的答案。我已经建议了他们应该如何解决这个问题,所以我认为将其视为答案是合理的。 (4认同)