当我尝试用波兰语格式化日期时,我得到了一致的格式:
new SimpleDateFormat("EEEE", Locale.forLanguageTag("pl-PL")).format(new Date())
结果
wtorek
bash 中的相同结果:
LC_ALL=pl_PL
$ date +"%A %b %d"
wtorek maj 22
注意 wtorek
中的小写 w
。
当我对捷克语执行此操作时,结果不一致:
new SimpleDateFormat("EEEE", Locale.forLanguageTag("cs-CZ").format(new Date())
结果
Pondělí
在 bash 中运行时:
$ LC_ALL=cs_CZ
$ date +"%A %b %d"
pondělí kvě 21
注意 Java 结果中的大写 P
。这是怎么发生的?这是否意味着 SimpleDateFormat
不使用系统上安装的标准语言环境?
最佳答案
Java 从最多四个来源获取其语言环境数据(包括不同语言环境中星期几的名称)。是的,主机操作系统是其中之一,但不是默认的。引用the LocaleServiceProvider
documentation :
Java Runtime Environment provides the following four locale providers:
- "CLDR": A provider based on Unicode Consortium's CLDR Project.
- "COMPAT": represents the locale sensitive services that is compatible with the prior JDK releases up to JDK8 (same as JDK8's "JRE").
- "SPI": represents the locale sensitive services implementing the subclasses of this LocaleServiceProvider class.
- "HOST": A provider that reflects the user's custom settings in the underlying operating system. This provider may not be available, depending on the Java Runtime Environment implementation.
- "JRE": represents a synonym to "COMPAT". This name is deprecated and will be removed in the future release of JDK.
默认为 Java 8 JRE。我正在使用 java.time
,因为没有人应该为过时的 SimpleDateFormat
而烦恼:
DateTimeFormatter dayOfWeekFormatter
= DateTimeFormatter.ofPattern("EEEE", Locale.forLanguageTag("cs-CZ"));
LocalDate date = LocalDate.now(ZoneId.of("Europe/Prague"));
System.out.println(date.format(dayOfWeekFormatter));
在我的 Oracle jdk1.8.0_131 上运行的输出与您的结果一致(大写 S
):
Středa
我们可以通过系统属性控制使用的语言环境数据。例如,要更喜欢 CLDR,可以使用 VM 命令行选项 -Djava.locale.providers=CLDR,COMPAT
运行程序,或者在程序开头插入以下行:
System.setProperty("java.locale.providers", "CLDR,COMPAT");
středa
现在我们得到小写的 s
。
我在 macOS Sierra 10.12.6 上的 shell 只给出了 Wednesday
,所以显然我的操作系统没有捷克语言环境数据(这听起来很奇怪;可能问题出在其他地方),因此不是我的一个选择。您可以尝试将 HOST
放在上面的语言环境提供程序字符串前面,看看您得到的内容是否与您的 bash
一致。
在 Java 9 及更高版本中,CLDR 是默认值。因此,在不设置任何系统属性的情况下在 jdk9.0.4 上运行相同的代码片段也会以小写字母显示星期几:
středa
关于java - 与 Bash 相比,Java 中的语言环境区分大小写不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470034/