我需要将工作日名称解析为DayOfWeek
。
周日名称可以是简短('Mon')或long('Monday')格式。
目前我已经提出了这样的解决方案:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE", locale);
DayOfWeek dayOfWeek;
try {
dayOfWeek = DayOfWeek.from(dtf.parse(value));
}
catch (DateTimeException e) {
dtf = DateTimeFormatter.ofPattern("EEEE", locale);
dayOfWeek = DayOfWeek.from(dtf.parse(value));
}
是否有更短的解决方案?
答案 0 :(得分:4)
您可以将DateTimeFormatterBuilder
与可选模式一起使用。这些将按您附加的顺序进行尝试。如果所有模式都失败,仍会抛出DateTimeException
。
final DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern("EEEE"))
.appendOptional(DateTimeFormatter.ofPattern("E"))
.toFormatter(locale);
final DayOfWeek dow1 = DayOfWeek.from(dtf.parse("Mon"));
final DayOfWeek dow2 = DayOfWeek.from(dtf.parse("Monday"));
请注意,如果您愿意,结果DayOfWeek
现在可以是最终的。
跨多种语言(多个语言环境)尝试相同的代码。
for ( final Locale locale : new Locale[] { Locale.US , Locale.CANADA_FRENCH , Locale.ITALY , Locale.KOREA } ) {
final String inputShort = ( DayOfWeek.MONDAY.getDisplayName ( TextStyle.SHORT, locale ) );
final String inputFull = ( DayOfWeek.MONDAY.getDisplayName ( TextStyle.FULL, locale ) );
final DateTimeFormatter dtf = new DateTimeFormatterBuilder ( )
.appendOptional ( DateTimeFormatter.ofPattern ( "EEEE" ) )
.appendOptional ( DateTimeFormatter.ofPattern ( "E" ) )
.toFormatter ( locale );
final DayOfWeek dow1 = DayOfWeek.from ( dtf.parse ( inputShort ) );
final DayOfWeek dow2 = DayOfWeek.from ( dtf.parse ( inputFull ) );
System.out.println ( "" );
System.out.println ( "Language: " + locale.getDisplayLanguage ( Locale.US ) );
System.out.println ( "inputShort: " + inputShort + " | dow1: " + dow1 );
System.out.println ( "inputFull: " + inputFull + " | dow2: " + dow2 );
}
跑步时。
Language: English
inputShort: Mon | dow1: MONDAY
inputFull: Monday | dow2: MONDAY
Language: French
inputShort: lun. | dow1: MONDAY
inputFull: lundi | dow2: MONDAY
Language: Italian
inputShort: lun | dow1: MONDAY
inputFull: lunedì | dow2: MONDAY
Locale: Korean
inputShort: 월 | dow1: MONDAY
inputFull: 월요일 | dow2: MONDAY
答案 1 :(得分:0)
不要使用try-catch
来做条件。 catch
是slow。条件更适合if
。
final static DateTimeFormatter shortDTF = DateTimeFormatter.ofPattern("EEE", locale);
final static DateTimeFormatter longDTF = DateTimeFormatter.ofPattern("EEEE", locale);
TemporalAccessor parsed;
try{
if(value.length() > 3){
parsed = longDTF.parse(value)
} else {
parsed = shortDTF.parse(value)
}
dayOfWeek = DayOfWeek.from(parsed);
} catch(DateTimeException e){
// throw exception here
}
如果您使用100,000次分析进行性能测试,if
语句会更快。