gpt4 book ai didi

java - 如何将具有不同模式的星期名称解析为 DayOfWeek?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:03:54 25 4
gpt4 key购买 nike

我需要将工作日名称解析为 DayOfWeek。工作日名称可以是短格式('Mon')或长格式('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));
}

有更短的解决方案吗?

最佳答案

您可以将 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

关于java - 如何将具有不同模式的星期名称解析为 DayOfWeek?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42980743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com