Is there a reverse function for DayOfWeek :: getDisplayName ()

I need a converter that converts DayOfWeek

to String

, and vice versa, given some Locale

and TextStyle

. One way is straight forward:

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

      

I didn't find any useful methods in the package otherwise java.time

. I'm looking for something like LocalDate::parse(CharSequence text, DateTimeFormatter formatter)

but for DayOfWeek

.

+3


source to share


1 answer


DayOfWeek

doesn't have a method parse

, but you can build DateTimeFormatter

and use it with DayOfWeek::from

for parsing 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 DayOfWeek

from created String

:

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())

      

+3


source







All Articles