用泰文数字显示 Java 中的日期时间
Display date time in Java with Thai numerals
这个练习来自 Horstmann 的书 Core Java for the impatient:
Write a program that demonstrates the date and time formatting styles in [...] Thailand (with Thai digits).
我尝试使用以下代码片段解决练习:
Locale locale = Locale.forLanguageTag("th-TH-TH");
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(formatter.withLocale(locale).format(dateTime));
问题是虽然月份的名称用泰语正确给出(至少我是这么认为的,因为我不懂泰语),数字仍然用阿拉伯数字格式化,输出如下:
3 ก.ย. 2017, 22:42:16
我尝试了不同的语言标签("th-TH"
、"th-TH-TH"
、"th-TH-u-nu-thai"
)但无济于事。我应该更改什么以使程序按预期运行?我在 Windows 10 64 位上使用 JDK 1.8.0_131。
DateTimeFormatter::withDecimalStyle
我能够解决这个问题。必须像这样传递一个 DecimalStyle
to the formatter by calling DateTimeFormatter::withDecimalStyle
(请参阅 bold 中的代码进行更改):
Locale locale = Locale.forLanguageTag("th-TH-u-nu-thai");
LocalDateTime dateTime = LocalDateTime.now();
<b>DecimalStyle style = DecimalStyle.of(locale);</b>
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(formatter.withLocale(locale)<b>.withDecimalStyle(style)</b>.format(dateTime));
这个练习来自 Horstmann 的书 Core Java for the impatient:
Write a program that demonstrates the date and time formatting styles in [...] Thailand (with Thai digits).
我尝试使用以下代码片段解决练习:
Locale locale = Locale.forLanguageTag("th-TH-TH");
LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(formatter.withLocale(locale).format(dateTime));
问题是虽然月份的名称用泰语正确给出(至少我是这么认为的,因为我不懂泰语),数字仍然用阿拉伯数字格式化,输出如下:
3 ก.ย. 2017, 22:42:16
我尝试了不同的语言标签("th-TH"
、"th-TH-TH"
、"th-TH-u-nu-thai"
)但无济于事。我应该更改什么以使程序按预期运行?我在 Windows 10 64 位上使用 JDK 1.8.0_131。
DateTimeFormatter::withDecimalStyle
我能够解决这个问题。必须像这样传递一个 DecimalStyle
to the formatter by calling DateTimeFormatter::withDecimalStyle
(请参阅 bold 中的代码进行更改):
Locale locale = Locale.forLanguageTag("th-TH-u-nu-thai");
LocalDateTime dateTime = LocalDateTime.now();
<b>DecimalStyle style = DecimalStyle.of(locale);</b>
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(formatter.withLocale(locale)<b>.withDecimalStyle(style)</b>.format(dateTime));