Cannot parse German day of week abbreviation with SimpleDateFormat

Viewed 536

I want to parse German day of week like Mo, Di, Mi, Do, Fr, Sa, So. I'm using SimpleDateFormat class which allows us to choose locale. My parsing method looks like this:

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);
}

Everytime when I try to parse this abbreviation for day of week I become ParseException:

java.text.ParseException: Unparseable date: "Mo"
    at java.base/java.text.DateFormat.parse(DateFormat.java:395)

The thing is that in another class I'm using DayOfWeek enum to create the same abbreviation for German day of week and it's making correct abbreviation Mo, Di, Mi, Do, Fr, Sa, So:

DayOfWeek in = DayOfWeek.of(fromInt);
string.append(in.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.GERMANY));

Am I doing something wrong?

1 Answers

Try printing the result for formatting dates using that SimpleDateFormat to see what it expects.

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);
}

Output (using Java 9.0.4, 10.0.2, 11.0.2, 12.0.1, 13.0.2)

Mo.
Di.
Mi.
Do.
Fr.
Sa.
So.

Output (using Java 1.7.0_75, 1.8.0_181)

Mo
Di
Mi
Do
Fr
Sa
So

As you can see, Java 9+ expects the 2-letter day-of-week name to be followed by a . period.

Related