微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Unparseable希腊语日期 – SimpleDateFormat

我正在尝试使用SimpleDateFormat读取表示希腊语日期时间的字符串(如“28Μαρτίου2014,14:00”),但它会抛出 java.text.ParseException:Unparseable date:“28Μαρτίου2014,14:00 “错误.

这是一个示例代码

Locale locale = new Locale("el-GR");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy,HH:mm",locale);
try {
     sDate = (Date) formatter.parse("28 Μαρτίου 2014,14:00");
 } catch (ParseException ex) {
     ex.printstacktrace();
 }

我也试过locales el和el_GR,但没有运气.

有什么建议?

解决方法

a)首先要说的是,永远不要使用表达式新的Locale(“el-GR”),而是使用新的Locale(“el”,“GR”)或没有国家/地区新的Locale(“el”),请参阅javadoc以正确使用构造函数(因为没有语言代码“el-GR”).

b)您观察到的异常(以及我,但不是每个人)都是由底层JVM的不同本地化资源引起的.我的JVM证明(1.6.0_31):

Locale locale = new Locale("el");
DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale);
for (String m : dfs.getMonths()) {
    System.out.println(m);
}

// output
Μάρτιος
Απρίλιος
Μάϊος
Ιούνιος
Ιούλιος
Αύγουστος
Σεπτέμβριος
Οκτώβριος
Νοέμβριος
Δεκέμβριος

可以在CLDR-repository中找到有关不同数据的说明,以获取本地化资源.现代希腊语知道3月份的至少两种不同形式(Μαρτίουvs独立形式Μάρτιος). Java-version 6使用独立形式,而Java-version 7使用普通形式.

另请参阅此compatibility note for java-version 8,其中您可以选择指定格式模式(独立或不单独):

When formatting date-time values using DateFormat and
SimpleDateFormat,context sensitive month names are supported for
languages that have the formatting and standalone forms of month
names. For example,the preferred month name for January in the Czech
language is ledna in the formatting form,while it is leden in the
standalone form. The getMonthNames and getShortMonthNames methods of
DateFormatSymbols return month names in the formatting form for those
languages. Note that the month names returned by DateFormatSymbols
were in the standalone form until Java SE 7
. You can specify the
formatting and/or standalone forms with the Calendar.getdisplayName
and Calendar.getdisplayNames methods…

所以显而易见的解决方案是更新到Java 7.外部库在这里没有帮助,因为今天没有一个人拥有自己的希腊语资源.但是,如果您因任何原因被迫继续使用Java 6,那么遵循笨拙的解决方法将有助于:

Locale locale = new Locale("el","GR");
SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy,locale);
DateFormatSymbols dfs = DateFormatSymbols.getInstance(locale);
String[] months = {"Ιανουαρίου","Φεβρουαρίου","Μαρτίου","Απριλίου","Μαΐου","Ιουνίου","Ιουλίου","Αυγούστου","Σεπτεμβρίου","Οκτωβρίου","Νοεμβρίου","Δεκεμβρίου"};
dfs.setMonths(months);
formatter.setDateFormatSymbols(dfs);

try {
     System.out.println(formatter.parse("28 Μαρτίου 2014,14:00"));
     // output in my timezone: Fri Mar 28 14:00:00 CET 2014
} catch (ParseException ex) {
     ex.printstacktrace();
}

原文地址:https://www.jb51.cc/java/124320.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐