多语言环境下,使用SimpleDateFormat格式化时间字符串的时候,不能正确显示阿拉伯数字

753 阅读2分钟

在设置系统语言为阿拉伯语后,调用String.format后会自动使用东阿拉伯数字,现在我们需要显示为西阿拉伯数字应该怎么办呢?

在项目中遇到过系统有多语言应用的环境,当系统语言设置为阿拉伯语等其他部分语言的时候,使用 SimpleDateFormat格式化时间即:

74560c2aedf64603344b8d7d23453d2.png

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now=new Date();
System.out.println(sdf .format(now));

这时候得到的字符串显示为:٢٠١٥-٠٩-١٨ ٠٧:٠٣:٤٩ 这个明显不是我想要的结果,查阅资料发现,SimpleDateFormat有一个构造函数是带Locale参数的,于是在构造函数中添加一个Locale参数:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);

指定一下语言环境,这样得到的字符串就为:2015-09-18 07:10:45

纯数字

int i =٥٠;
NumberFormat nf=NumberFormat.getInstance(Locale.ENGLISH);//强制英语格式
String nn = nf.format(i);

格式化字符

String.format(Locale.ENGLISH,"%1$d", num)

字符强转

/**
*输入带东阿拉伯数字的string,可转化成西阿拉伯数字
*/
public static String replaceNonstandardDigits(String input) {
    if (input == null || input.isEmpty()) {
        return input;
    }

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
        if (isNonstandardDigit(ch)) {
            int numericValue = Character.getNumericValue(ch);
            if (numericValue >= 0) {
                builder.append(numericValue);
            }
        } else {
            builder.append(ch);
        }
    }
    return builder.toString();
}

public static boolean isNonstandardDigit(char ch) {
    return Character.isDigit(ch) && !(ch >= '0' && ch <= '9');
}

  1. 使用翻转图标的方法 在一些情况下,我们可以通过翻转图标的方式来适配阿拉伯语左右舵方向图标。例如,如果一个图标是从左到右的箭头,那么在阿拉伯语环境下,我们可以将其翻转成从右到左的箭头。
// Java代码
ImageView imageView = findViewById(R.id.imageView);

if (isArabicLocale()) {
    imageView.setScaleX(-1);
} else {
    imageView.setScaleX(1);
}
/**
 * 阿拉伯的数字 采用0123456789
 * @param original
 * @return
 */
public static String replaceArabicNumbers(String original) {
    return original.replaceAll("١","1")
            .replaceAll("٢","2")
            .replaceAll("٣","3")
            .replaceAll("٤","4")
            .replaceAll("٥","5")
            .replaceAll("٦","6")
            .replaceAll("٧","7")
            .replaceAll("٨","8")
            .replaceAll("۹","9")
            .replaceAll("٠","0");
}

关于java:android:gravity =” right”不适用于阿拉伯语和其他RTL语言的所有设备, 用end

android:gravity="start"
android:textAlignment="viewStart"
android:textDirection="locale"