我尝试使用 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
我做错了什么?
最佳答案
尽管在英语中,单独使用的日期名称与在日期上下文中使用的名称之间没有区别,但在德语中,显然是有区别的。
模式eee
对应于TextStyle.SHORT
,而模式ccc
对应于TextStyle.SHORT_STANDALONE
。因此,如果您尝试解析由 TextStyle.SHORT_STANDALONE
使用 eee
在重要语言中创建的日期名称,解析将会失败。
对于独立版本,可行的方法是 ccc
。
提到这一点的文档实际上在 DateTimeFormatterBuilder
中API 而不是 DateTimeFormatter
的。
关于java - 解析工作日不适用于德语区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57167289/