Android日期時間格式國際化的實現(xiàn)代碼
在做多語言版本的時候,日期時間的格式話是一個很頭疼的事情,幸好Android提供了DateFormate,可以根據(jù)指定的語言區(qū)域的默認格式來格式化。
直接貼代碼:
public static CharSequence formatTimeInListForOverSeaUser(
final Context context, final long time, final boolean simple,
Locale locale) {
final GregorianCalendar now = new GregorianCalendar();
// special time
if (time < MILLSECONDS_OF_HOUR) {
return "";
}
// today
final GregorianCalendar today = new GregorianCalendar(
now.get(GregorianCalendar.YEAR),
now.get(GregorianCalendar.MONTH),
now.get(GregorianCalendar.DAY_OF_MONTH));
final long in24h = time - today.getTimeInMillis();
if (in24h > 0 && in24h <= MILLSECONDS_OF_DAY) {
java.text.DateFormat df = java.text.DateFormat.getTimeInstance(
java.text.DateFormat.SHORT, locale);
return "" + df.format(time);
}
// yesterday
final long in48h = time - today.getTimeInMillis() + MILLSECONDS_OF_DAY;
if (in48h > 0 && in48h <= MILLSECONDS_OF_DAY) {
return simple ? context.getString(R.string.fmt_pre_yesterday)
: context.getString(R.string.fmt_pre_yesterday)
+ " "
+ java.text.DateFormat.getTimeInstance(
java.text.DateFormat.SHORT, locale).format(
time);
}
final GregorianCalendar target = new GregorianCalendar();
target.setTimeInMillis(time);
// same week
if (now.get(GregorianCalendar.YEAR) == target
.get(GregorianCalendar.YEAR)
&& now.get(GregorianCalendar.WEEK_OF_YEAR) == target
.get(GregorianCalendar.WEEK_OF_YEAR)) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("E", locale);
final String dow = "" + sdf.format(time);
return simple ? dow : dow
+ java.text.DateFormat.getTimeInstance(
java.text.DateFormat.SHORT, locale).format(time);
}
// same year
if (now.get(GregorianCalendar.YEAR) == target
.get(GregorianCalendar.YEAR)) {
return simple ? java.text.DateFormat.getDateInstance(
java.text.DateFormat.SHORT, locale).format(time)
: java.text.DateFormat.getDateTimeInstance(
java.text.DateFormat.SHORT,
java.text.DateFormat.SHORT, locale).format(time);
}
return simple ? java.text.DateFormat.getDateInstance(
java.text.DateFormat.SHORT, locale).format(time)
: java.text.DateFormat.getDateTimeInstance(
java.text.DateFormat.SHORT, java.text.DateFormat.SHORT,
locale).format(time);
}
注意這里用的是java.text.DateFormat,還有另外一個java.text.format.DateFormat,后者不能指定locale。
詳細介紹見:http://developer.android.com/reference/java/text/DateFormat.html
相關(guān)文章
Android控件ImageSwitcher實現(xiàn)左右圖片切換功能
這篇文章主要為大家詳細介紹了Android控件ImageSwitcher實現(xiàn)左右圖片切換功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-05-05
關(guān)于Android Fragment對回退棧的詳細理解
這篇文章主要介紹了Android Fragment的回退棧示例詳細介紹的相關(guān)資料,在Android中Fragment回退棧是由Activity管理的,每個Activity都有自己的回退棧,其中保存了已經(jīng)停止(處于后臺)的Fragment實例,需要的朋友可以參考下2016-12-12
Android UI設(shè)計之AlertDialog彈窗控件
這篇文章主要為大家詳細介紹了Android UI設(shè)計之AlertDialog彈窗控件的使用方法,感興趣的小伙伴們可以參考一下2016-08-08
Android開發(fā)之5.0activity跳轉(zhuǎn)時共享元素的使用方法
下面小編就為大家分享一篇Android開發(fā)之5.0activity跳轉(zhuǎn)時共享元素的使用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01

