我想解析德语星期几,如Mo、Di、Mi、Do、Fr、Sa、So
。我正在使用SimpleDateFormat
类,它允许我们选择语言环境。我的解析方法如下所示:
private static int parseDayOfWeek(String day) {
SimpleDateFormat dayFormat = new SimpleDateFormat("EEE", Locale.GERMANY);
Date date = null;
try {
date = dayFormat.parse(day);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
每次当我尝试解析这个星期几的缩写时,我都会变成ParseException
:
java.text.ParseException: Unparseable date: "Mo"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
问题是,在另一个类中,我使用DayOfYork枚举为德语星期创建相同的缩写,它使正确的缩写Mo, Di,Mi,Do,Fr,Sa,So
:
DayOfWeek in = DayOfWeek.of(fromInt);
string.append(in.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.GERMANY));
我做错什么了吗?
尝试使用SimpleDateFormat
打印格式化日期的结果以查看它的期望。
SimpleDateFormat dayFormat = new SimpleDateFormat("EEE", Locale.GERMANY);
Calendar cal = Calendar.getInstance();
for (int i = 0; i < 7; i++) {
System.out.println(dayFormat.format(cal.getTime()));
cal.add(Calendar.DAY_OF_MONTH, 1);
}
输出(使用Java9.0.4、10.0.2、11.0.2、12.0.1、13.0.2)
Mo.
Di.
Mi.
Do.
Fr.
Sa.
So.
输出(使用Java1.70_75、1.80_181)
Mo
Di
Mi
Do
Fr
Sa
So
如您所见,Java9期望2个字母的星期名称后面跟着一个.
句点。