【问题标题】:How to localize numbers with DateTimeFormatter?如何使用 DateTimeFormatter 本地化数字?
【发布时间】:2020-10-08 05:42:19
【问题描述】:

java.time.format.DateTimeFormatter 类在使用不同符号表示数字的语言环境中无法正常工作。

波斯语(也称为波斯语)等语言使用不同的符号和 Unicode 字符来表示数字:
波斯数字:0 1 2 3 4 5 ۶ 7 ۸ ۹
西方数字: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 旧版 Dates 的 DateFormat 类按预期工作。

【问题讨论】:

    标签: java localization datetime-format java-time localdate


    【解决方案1】:

    这已在JDK 15 中修复。使用localizedBy()(而不是localizedWith()):

    formatter
        .localizedBy(myLocale)
        .format(...)
    

    对于 Java 版本

    formatter
        .localizedBy(myLcoale)
        .withDecimalStyle(DecimalStyle.of(myLocale))
        .format(...)
    

    【讨论】:

    • localizedBy其实是在JDK 10中引入的
    • 链接已更新。你是对的。 LocalizedBy 是在 JDK 10 中引入的,但修复是在 JDK 15 中实现的(可能向后移植到早期的 Java 版本)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 2013-03-17
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多