如何使用 DateTimeFormatter 本地化数字?
How to localize numbers with DateTimeFormatter?
对于使用不同符号表示数字的语言环境,java.time.format.DateTimeFormatter
class 无法正常工作。
波斯语(也称为波斯语)等语言使用不同的符号和 Unicode 字符来表示数字:
波斯数字:0 1 2 3 4 5 6 7 8 9
西方数字:0 1 2 3 4 5 6 7 8 9
例如:
Locale myLocale = Locale.forLanguageTag("fa");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy", myLocale);
formatter.format(LocalDate.now()); // should return "۲۰۲۰" but returns "2020"
我应该说,用于格式化 Java 遗留 Date
的 DateFormat
class 按预期工作。
这已在 JDK 15 中修复。使用 localizedBy()
(而非 localizedWith()
):
formatter
.localizedBy(myLocale)
.format(...)
对于 Java 版本 < 15 格式如下:
formatter
.localizedBy(myLcoale)
.withDecimalStyle(DecimalStyle.of(myLocale))
.format(...)
对于使用不同符号表示数字的语言环境,java.time.format.DateTimeFormatter
class 无法正常工作。
波斯语(也称为波斯语)等语言使用不同的符号和 Unicode 字符来表示数字:
波斯数字:0 1 2 3 4 5 6 7 8 9
西方数字:0 1 2 3 4 5 6 7 8 9
例如:
Locale myLocale = Locale.forLanguageTag("fa");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy", myLocale);
formatter.format(LocalDate.now()); // should return "۲۰۲۰" but returns "2020"
我应该说,用于格式化 Java 遗留 Date
的 DateFormat
class 按预期工作。
这已在 JDK 15 中修复。使用 localizedBy()
(而非 localizedWith()
):
formatter
.localizedBy(myLocale)
.format(...)
对于 Java 版本 < 15 格式如下:
formatter
.localizedBy(myLcoale)
.withDecimalStyle(DecimalStyle.of(myLocale))
.format(...)