在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;
}
}
显示效果: