我正在尝试使用 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},ISO
input: Di, parsed: {DayOfWeek=2},ISO
但我实际上得到
input: Dienstag, parsed: {DayOfWeek=2},ISO
Exception 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)
请注意,当我将语言环境更改为Locale.forLanguageTag("en")有效时,输出为
input: Tuesday, parsed: {DayOfWeek=2},ISO
input: Tue, parsed: {DayOfWeek=2},ISO
我究竟做错了什么?
撒科打诨
相关分类