luk*_*keg 6 java datetime localization datetime-format
这个练习来自Horstmann的书籍Core Java,因为他不耐烦:
编写一个程序,演示[...]泰国的日期和时间格式样式(泰语数字).
我尝试使用以下代码解决练习:
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));
Run Code Online (Sandbox Code Playgroud)
问题是虽然月份的名称是用泰语给出的(至少我是这么认为的,因为我不懂泰语),数字仍然用阿拉伯数字格式化,输出如下:
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
调用将 a 传递给格式化程序DateTimeFormatter::withDecimalStyle
,如下所示(有关更改,请参阅粗体代码):
Locale locale = Locale.forLanguageTag("th-TH-u-nu-thai");
LocalDateTime dateTime = LocalDateTime.now();
DecimalStyle style = DecimalStyle.of(locale);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
System.out.println(formatter.withLocale(locale).withDecimalStyle(style).format(dateTime));