Search code examples
javalocaledate-parsingjava-time

Parsing of weekdays not working for locale german


I'm trying to use java.time.format.DateTimeFormatter to parse time strings but ran into a problem parsing german short day of week names.

Given the following program

import java.time.DayOfWeek;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;

var locale = Locale.forLanguageTag("de");
var dtf = new DateTimeFormatterBuilder()
        .appendOptional(DateTimeFormatter.ofPattern("eeee"))
        .appendOptional(DateTimeFormatter.ofPattern("eee"))
        .toFormatter(locale);
var input1 = DayOfWeek.TUESDAY.getDisplayName(TextStyle.FULL, locale);
var input2 = DayOfWeek.TUESDAY.getDisplayName(TextStyle.SHORT_STANDALONE, locale);
System.out.printf("input: %s, parsed: %s\n", input1, dtf.parse(input1));
System.out.printf("input: %s, parsed: %s\n", input2, dtf.parse(input2));

the output I would expect is

input: Dienstag, parsed: {DayOfWeek=2},ISO
input: Di, parsed: {DayOfWeek=2},ISO

but I actually get

input: Dienstag, parsed: {DayOfWeek=2},ISO
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Di' could not be parsed, unparsed text found at index 0
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1874)
    at org.rksm.Main.main(Main.java:22)

Note that when I change the locale to Locale.forLanguageTag("en") it works and the output is

input: Tuesday, parsed: {DayOfWeek=2},ISO
input: Tue, parsed: {DayOfWeek=2},ISO

What am I doing wrong?


Solution

  • Although in English there is no difference between the name of the day when it is used alone and the name as it is used within the context of a date, in German, apparently, there is.

    The pattern eee corresponds to TextStyle.SHORT, while the pattern ccc corresponds to TextStyle.SHORT_STANDALONE. Thus, if you try to parse a day name that was created by TextStyle.SHORT_STANDALONE with eee in the languages where it matters, the parsing will fail.

    The way to go is ccc for the standalone version.

    The documentation mentioning this is actually in the DateTimeFormatterBuilder API rather than DateTimeFormatter's.