2017-05-29 67 views
3

我需要转换成DayOfWeek一个String转换器和给周围的其他方式的一些LocaleTextStyle。 一种方法是直截了当:有星期几的反函数:: getDisplayName()

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

对于我没有找到在java.time包的任何有用的方法的另一种方式。我正在寻找类似LocalDate::parse(CharSequence text, DateTimeFormatter formatter)但是DayOfWeek

+2

如果你的'DateTimeFormatter'在它的模式中有星期几,那么解析就做你想要的。 –

回答

3

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

谢谢!正是我在找什么。我没有意识到'DateTimeFormatterBuilder'-API ...看起来相当强大:-) –

+0

的确,这是一个非常强大且有用的类! – 2017-05-29 17:14:29

+1

非常优雅和一般。 –