【问题标题】:Parsing of weekdays not working for locale german工作日的解析不适用于语言环境德语
【发布时间】: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


【解决方案1】:

虽然在英语中单独使用的日期名称和在日期上下文中使用的日期名称之间没有区别,但在德语中,显然是有区别的。

模式eee 对应于TextStyle.SHORT,而模式ccc 对应于TextStyle.SHORT_STANDALONE。因此,如果您尝试用重要的语言解析由TextStyle.SHORT_STANDALONEeee 创建的日期名称,解析将失败。

独立版的方法是ccc

提到这一点的文档实际上是在DateTimeFormatterBuilder API 而不是DateTimeFormatter 的。

【讨论】:

  • 那是真的:TextStyle.SHORTDi. 一个点,SHORT_STANDALONE 只是Di 没有点(在我的Java 11 上使用默认设置;我怀疑设置系统属性@987654335 @ 会改变结果)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多