3

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?

Dawid
  • 347
  • 2
  • 15

1 Answers1

1

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • The thing is that now after parse `Mo.` I become integer of `2` instead of `1`. I know that in Germany the first day of week is Monday, not Sunday. Can I define during parsing which day of week should be first? – Dawid Mar 09 '20 at 15:22
  • 1
    @Dawid `Calendar.MONDAY` is the value `2`, so it's supposed to return `2` for a Monday. The javadoc of [`Calendar.DAY_OF_WEEK`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#DAY_OF_WEEK) says: *Field number for `get` and `set` indicating the day of the week. This field takes values `SUNDAY`, `MONDAY`, `TUESDAY`, `WEDNESDAY`, `THURSDAY`, `FRIDAY`, and `SATURDAY`.* --- It does not define any meaning for the numerical value, only that the value is one of the 7 constants. The javadoc doesn't even show what the numerical values are. – Andreas Mar 09 '20 at 15:29