本地化数字和日期格式,但不本地化数字符号

我有一个用例,我想根据用户区域设置显示日期和数字。

我正在分别使用DateFormat.getDateInstance(DateFormat.MEDIUM,locale)和NumberFormat.getNumberInstance(locale)。

我面临的问题是,DateFormat和NumberFormat也在根据语言环境更改数字,这不是我想要的。希望最终的字符串仅使用阿拉伯数字(0-9)。

例如,

对于一个值,为53.54 在hi_IN中,它变成५३.५४

在de_DE中,它变为53,54

我希望它像

在hi_IN中,53.54

de_DE,53,54

是否使用。或,因为小数点分隔符应基于语言环境,但数字应为阿拉伯语。 在日期转换中面临类似的问题。

感谢您的帮助!

lugogogo 回答:本地化数字和日期格式,但不本地化数字符号

虽然我无法重现您描述的行为,但可以向您展示如何控制格式化程序使用的数字。

    NumberFormat nf = NumberFormat.getNumberInstance();
    if (nf instanceof DecimalFormat) {
        DecimalFormat df = (DecimalFormat) nf;

        // Hindi digits
        char ch0 = '\u0966'; // Hindi zero
        DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
        symbols.setZeroDigit(ch0);
        df.setDecimalFormatSymbols(symbols);
        System.out.println(nf.format(53.54));

        // Western digits
        symbols.setZeroDigit('0'); // Western zero
        df.setDecimalFormatSymbols(symbols);
        System.out.println(nf.format(53.54));
    } else {
        System.out.println("Cannot control digits for this formatter");
    }

在我的计算机上,此代码段的输出是:

५३.५४
53.54

我们仅指定零位数字,即用于0的字符。格式化程序会从中指出其他数字本身。

对于格式化日期,我非常热烈地推荐java.time,现代的Java日期和时间API及其DateTimeFormatter

    DateTimeFormatter dateFormatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.GERMAN);

    // Hindi digits
    DecimalStyle style = dateFormatter.getDecimalStyle().withZeroDigit(ch0);
    DateTimeFormatter hindiDateFormatter = dateFormatter.withDecimalStyle(style);
    System.out.println(LocalDate.now(ZoneId.of("Europe/Vienna")).format(hindiDateFormatter));

    // Western digits
    style = dateFormatter.getDecimalStyle().withZeroDigit('0');
    DateTimeFormatter westernDateFormatter = dateFormatter.withDecimalStyle(style);
    System.out.println(LocalDate.now(ZoneId.of("Europe/Zurich")).format(westernDateFormatter));
१२.१२.१९
12.12.19

众所周知,您在问题中尝试使用的DateFormat类很麻烦,而且已经过时了。

链接: Oracle tutorial: Date Time解释了如何使用java.time。

本文链接:https://www.f2er.com/2946862.html

大家都在问