'String input of weekdays in German to Localdate

I have a string input of weekdays in German and need to get the next Localdate after today which corresponds to the given weekday string. If for example the input is Montag (Monday) I need the output as Localdate of 2022-05-16 which is the next Monday after today. If the input was in english I could do something like:

String input = "Monday";

LocalDate today       = LocalDate.now();
LocalDate nextWeekday = today.with(TemporalAdjusters.next(DayOfWeek.valueOf(input.toUpperCase())));

System.out.println(nextWeekday);

Is there something I can do, may be using Locale, to use strings (days) given in German to get the next weekday as a Localdate? If possible without defining my own Enum? I would want to avoid doing

public enum DayOfWeekGerman {
  MONTAG,
  DIENSTAG,
  MITTWOCH,
  ...
  //methods & getters
}

and map them somehow to use the java.time API methods like Localdate.with...



Solution 1:[1]

The classes of java.time are data classes. They do not have a locale. They happen to be English names only because the Java language itself is in English.

However, you can make a Map for looking up a DayOfWeek value from a name:

private static final Map<String, DayOfWeek> germanDaysOfWeek =
    Arrays.stream(DayOfWeek.values()).collect(
        Collectors.toMap(
            d -> d.getDisplayName(TextStyle.FULL, Locale.GERMAN), d -> d));

{Freitag=FRIDAY, Samstag=SATURDAY, Montag=MONDAY, Mittwoch=WEDNESDAY, Donnerstag=THURSDAY, Dienstag=TUESDAY, Sonntag=SUNDAY}

Perform a lookup on that map.

String input = "Montag";

LocalDate today = LocalDate.now();
LocalDate nextWeekday = today.with(
    TemporalAdjusters.next(germanDaysOfWeek.get(input)));

See all this code run live at Ideone.com.

2022-05-16

Solution 2:[2]

Considering today is 09/May/2022 (Monday), you can try :

String input = "Montag";
LocalDate today       = LocalDate.now();
DayOfWeek weekday = DayOfWeek.from(
        DateTimeFormatter.ofPattern("EEEE", Locale.GERMAN).parse(input));
LocalDate nextWeekday = today.with(TemporalAdjusters.next(weekday));
System.out.println(nextWeekday);

Output:

2022-05-16

If you execute it on any other day, you might get different output based on day & date.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Basil Bourque
Solution 2 Ole V.V.