我需要一个将DayOfWeek
转换为String
的转换器,反过来考虑一些Locale
和TextStyle
。
一种方法是直截了当的:
public String getAsString(DayOfWeek day, TextStyle style, Locale locale){
return day.getDisplayName(style, locale);
}
另一方面,我在java.time
包中找不到任何有用的方法。我正在寻找类似LocalDate::parse(CharSequence text, DateTimeFormatter formatter)
但DayOfWeek
。
答案 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())