Android 中国际化时间格式表示方式

在Android开发中,显示时间是非常常见的功能,若开发的App涉及到多语言,显示的时间的格式,则又是一个需要考虑的地方,下面就来说一说在Android开发中,时间显示多语言的适配.


1.日期,星期格式化可参考android.text.format.DateFormat类,基本上可通过其实现多语言的时间格式,具体如下:

//日期格式
String dateFormat = mCtx.getString(R.string.format_date_no_year);
DateFormat.format(dateFormat, new Date().getTime()
//星期格式
String weekFormat = mCtx.getString(R.string.format_week);
DateFormat.format(weekFormat, new Date().getTime()

在values/strings.xml下的值

<string name="format_date_no_year">MMMM d</string>
    <string name="format_week">EEEE</string>


在values-zh-rCN下的值

<string name="format_date_no_year">MM月d日</string>
    <string name="format_week">EEEE</string>
显示效果:



2.时间格式 

  public class Utils {
    private static final String TAG = Utils.class.getSimpleName();
    public static final String DEFAULT_FORMAT_12_HOUR = "h:mm a";
    public static final String DEFAULT_FORMAT_24_HOUR = "kk:mm";

    public static CharSequence getDateFormat(Context ctx, int amPmFontSize) {
    	//判断系统当前设置是12小时制还是24小时制
        final boolean format24Requested = DateFormat.is24HourFormat(ctx);
        CharSequence format;
        if (format24Requested) {
            format = get24ModeFormat();
        } else {
            format = get12ModeFormat(amPmFontSize);
        }
        return format;
    }

    /**
     * @param amPmFontSize - size of am/pm label (label removed is size is 0).
     * @return format string for 12 hours mode time
     */
    public static CharSequence get12ModeFormat(int amPmFontSize) {
        String pattern = DEFAULT_FORMAT_12_HOUR;
        // Remove the am/pm
        if (amPmFontSize <= 0) {
            pattern.replaceAll("a", "").trim();
        }
        // Replace spaces with "Hair Space"
        pattern = pattern.replaceAll(" ", "\u200A");
        // Build a spannable so that the am/pm will be formatted
        int amPmPos = pattern.indexOf('a');
        if (amPmPos == -1) {
            return pattern;
        }
        Spannable sp = new SpannableString(pattern);
        sp.setSpan(new StyleSpan(Typeface.NORMAL), amPmPos, amPmPos + 1, Spannable.SPAN_POINT_MARK);
        sp.setSpan(new AbsoluteSizeSpan(amPmFontSize), amPmPos, amPmPos + 1, Spannable.SPAN_POINT_MARK);
        sp.setSpan(new TypefaceSpan("sans-serif"), amPmPos, amPmPos + 1, Spannable.SPAN_POINT_MARK);
        return sp;
    }

    public static CharSequence get24ModeFormat() {
        return DEFAULT_FORMAT_24_HOUR;
    }

    }

显示效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值