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...
Advertisement
Answer
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