显示日期时间在Java中与泰国的数字
问题描述:
这个练习来自HORSTMANN的书Java核心的不耐烦:显示日期时间在Java中与泰国的数字
编写演示了[...]泰国日期与时间格式样式的程序(与泰国数字)。
我试着用下面的代码片段来解决exerciese:
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分十六秒
我尝试了不同的语言标签("th-TH"
,"th-TH-TH"
,"th-TH-u-nu-thai"
)无济于事。我应该改变什么才能使程序按照需要运行?我在Windows 10 64位上使用JDK 1.8.0_131。
答
DateTimeFormatter::withDecimalStyle
我能够解决的锻炼。我们必须通过调用DateTimeFormatter::withDecimalStyle
,像这样(见代码大胆更改)传递一个DecimalStyle
到格式:
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));
好问题和答案。但仅供参考,['LocalDateTime'](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html)故意丢弃时区信息。最好使用['ZonedDateTime'](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html)并保留有价值的信息。最好还是明确地将期望的/期望的时区传递给类的'.now(ZoneId)'方法,而不是隐式地依赖于JVM的当前默认时区,该时区可以在运行时随时更改。 –
这是一个有用的问题和答案,但它仍然让我想知道如果你无法理解输出,你将如何验证代码是否正确。 :) – ajb
@ajb输出看起来令人信服的非西方:) – lukeg