是否存在DayOfWeek :: getDisplayName()的反函数

时间:2017-05-29 13:55:12

标签: java java-8 java-time date-parsing

我需要一个将DayOfWeek转换为String的转换器,反过来考虑一些LocaleTextStyle。 一种方法是直截了当的:

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

另一方面,我在java.time包中找不到任何有用的方法。我正在寻找类似LocalDate::parse(CharSequence text, DateTimeFormatter formatter)DayOfWeek

的内容

1 个答案:

答案 0 :(得分:4)

DayOfWeek没有parse方法,但您可以构建DateTimeFormatter并将其与DayOfWeek::from一起使用来解析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);
}

有了这个,您可以从您创建的DayOfWeek获取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())