【发布时间】:2019-07-23 15:13:36
【问题描述】:
我正在尝试使用 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
我做错了什么?
【问题讨论】:
-
它是否适用于
Locale.GERMANY(或GERMAN)? -
请注意
eee代表TextStyle.SHORT,而ccc代表TextStyle.SHORT_STANDALONE。你试过ccc吗? -
RealSkeptic:确实,TextStyle.SHORT_STANDALONE / ccc 是要走的路。如果您将其发布为答案,我将其标记为这样。谢谢!
标签: java locale date-parsing java-time