带语言环境的日期格式

Date Format with Locale

我想根据每个国家的日期格式来显示日期。我试了很多方法终于找到了这个例子

http://www.java2s.com/Code/Java/Data-Type/DateFormatwithLocale.htm

这完美地表达了我的意思。 德国等一些国家不会使用12小时格式,而是使用24小时格式没有AM/PM。虽然 US 等一些国家/地区使用 12 小时格式。

但是我发现虽然 运行 这个 java class 它 returns 是预期的正确输出但是 运行 这个在 Android 投射它 returns 像这样

I/System.out: Locale: en_US
I/System.out: Jan 23, 2018 5:26:41 AM
I/System.out: Jan 23, 2018 5:26:41 AM
I/System.out: Jan 23, 2018 5:26:41 AM
I/System.out: Jan 23, 2018 5:26:41 AM
I/System.out: Jan 23, 2018 5:26:41 AM
I/System.out: Locale: de_DE
I/System.out: 23.01.2018 5:26:41 vorm.
I/System.out: 23.01.2018 5:26:41 vorm.
I/System.out: 23.01.2018 5:26:41 vorm.
I/System.out: 23.01.2018 5:26:41 vorm.
I/System.out: 23.01.2018 5:26:41 vorm.

在 Locale 的情况下:en_US 这是预期的,但在 Locale 的情况下:de_DE 预计不会有那个“蠕虫”。

谁能解释一下这种行为?

这是 java JDK 中的本机行为。

取决于您传递的有效区域设置,JDK 提供带有格式化日期的时间。

Returns 一个新的 DateFormat 实例,它使用指定语言环境的给定格式样式来格式化日期。

Parameters:
style the given formatting style. Either one of DateFormat.SHORT, 
DateFormat.MEDIUM, DateFormat.LONG, or DateFormat.FULL.
locale the desired locale.
Returns: a date formatter.
Throws: java.lang.IllegalArgumentException if style is invalid, or if locale isn't 
one of the locales returned from getAvailableLocales().
java.lang.NullPointerException if locale is null
See also: java.text.DateFormat.getDateInstance(int,java.util.Locale)

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/text/spi/DateFormatProvider.java#DateFormatProvider.getTimeInstance%28int%2Cjava.util.Locale%29

    LocalDateTime dateTime = LocalDateTime.of(2018, 1, 23, 5, 26, 41);
    DateTimeFormatter formatter = DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(Locale.GERMAN);
    System.out.println(dateTime.format(formatter));

版画

23.01.2018, 05:26:41

虽然没有在 Android 上测试,但我相信结果会是一样的。

java.time

您链接到的 java2s 页面上使用的 DateDateFormat 类 早已过时,尤其是后者也非常麻烦。仅出于这个原因,我建议您停止使用它们并开始使用 java.time,即现代 Java 日期和时间 API。与它一起工作要好得多。

你能在 Android 上做到吗?你当然可以。我被告知 java.time 内置于较新的 Android 设备上。对于旧设备,将 ThreeTenABP 添加到您的项目(请参阅底部的链接)并确保导入 org.threeten.bp.LocalDateTimeorg.threeten.bp.format.DateTimeFormatterorg.threeten.bp.format.FormatStyle。然后就可以了。

出了什么问题?

Java 从不同来源获取其语言环境信息。它在桌面 Java 和 Android Java 之间变化,它甚至可能在 Android 设备之间变化,并且在 Java 版本之间变化。没有任何保证,我认为 java.time 在这方面比旧的 类 更稳定。

链接

我终于找到了答案.. :) 谢谢 Ole V.V。

这里是: