java – 是否存在DayOfWeek :: getDisplayName()的反函数
作者:互联网
我需要一个将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.
解决方法:
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);
}
有了这个,您可以从您创建的String中获取DayOfWeek:
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())
标签:java,java-8,java-time,date-parsing 来源: https://codeday.me/bug/20190622/1265040.html