4

I need a converter that converts DayOfWeek into String and the other way around given some Locale and TextStyle. One way is straight forward:

public String getAsString(DayOfWeek day, TextStyle style, Locale locale){
    return day.getDisplayName(style, locale);
}

For the other way I did not find any useful methods in the java.time package. I'm looking for something like LocalDate::parse(CharSequence text, DateTimeFormatter formatter) but for DayOfWeek.

János
  • 153
  • 6

1 Answers1

4

DayOfWeek doesn't have a parse method, but you can build a DateTimeFormatter and use it with DayOfWeek::from to parse the String:

import java.time.temporal.ChronoField;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;

public DayOfWeek parseFromString(String str, TextStyle style, Locale locale) {
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        // Day of the week field, using the same TextStyle
        .appendText(ChronoField.DAY_OF_WEEK, style)
        // use the same locale
        .toFormatter(locale);
    // parse returns a TemporalAccessor, DayOfWeek::from converts it to a DayOfWeek object
    return formatter.parse(str, DayOfWeek::from);
}

With this, you can get the DayOfWeek from the String you created:

String dayOfWeekString = getAsString(DayOfWeek.MONDAY, TextStyle.FULL, Locale.US);
System.out.println(dayOfWeekString); // monday

DayOfWeek dayOfWeek = parseFromString(dayOfWeekString, TextStyle.FULL, Locale.US);
System.out.println(dayOfWeek); // MONDAY (return of DayOfWeek.toString())