我正在嘗試使用 java.time.format.DateTimeFormatter 來解析時間字符串,但在解析德語短星期幾名稱時遇到了問題。給定以下程序import java.time.DayOfWeek;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeFormatterBuilder;import java.time.format.TextStyle;import java.util.Locale;var locale = Locale.forLanguageTag("de");var dtf = new DateTimeFormatterBuilder() .appendOptional(DateTimeFormatter.ofPattern("eeee")) .appendOptional(DateTimeFormatter.ofPattern("eee")) .toFormatter(locale);var input1 = DayOfWeek.TUESDAY.getDisplayName(TextStyle.FULL, locale);var input2 = DayOfWeek.TUESDAY.getDisplayName(TextStyle.SHORT_STANDALONE, locale);System.out.printf("input: %s, parsed: %s\n", input1, dtf.parse(input1));System.out.printf("input: %s, parsed: %s\n", input2, dtf.parse(input2));我期望的輸出是input: Dienstag, parsed: {DayOfWeek=2},ISOinput: Di, parsed: {DayOfWeek=2},ISO但我實際上得到input: Dienstag, parsed: {DayOfWeek=2},ISOException in thread "main" java.time.format.DateTimeParseException: Text 'Di' could not be parsed, unparsed text found at index 0 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2049) at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1874) at org.rksm.Main.main(Main.java:22)請注意,當(dāng)我將語言環(huán)境更改為Locale.forLanguageTag("en")有效時,輸出為input: Tuesday, parsed: {DayOfWeek=2},ISOinput: Tue, parsed: {DayOfWeek=2},ISO我究竟做錯了什么?
1 回答

撒科打諢
TA貢獻1934條經(jīng)驗 獲得超2個贊
盡管在英語中單獨使用日期名稱和在日期上下文中使用的名稱之間沒有區(qū)別,但在德語中顯然是有區(qū)別的。
模式eee
對應(yīng)于TextStyle.SHORT
,而模式ccc
對應(yīng)于TextStyle.SHORT_STANDALONE
。因此,如果您嘗試在重要的語言中解析由TextStyle.SHORT_STANDALONE
with創(chuàng)建的日期名稱,解析將失敗。eee
要走的路是ccc
獨立版本。
提到這個的文檔實際上是在DateTimeFormatterBuilder
API 中而不是DateTimeFormatter
在 。
添加回答
舉報
0/150
提交
取消