在做多语言版本的时候,日期时间的格式话是一个很头疼的事情,幸好Android提供了DateFormate,可以根据指定的语言区域的默认格式来格式化。直接贴代码:
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

更多相关文章

  1. C语言函数的递归(上)
  2. Android多国语言文件夹
  3. android很的意思的事情,关于Input…
  4. Android实现多语言
  5. 【Android】多语言Values
  6. 使用MediaRecorder录制音频
  7. android/java中短信pdu编码
  8. android上传文件至服务器(android端+服务器端)
  9. Android全局主题样式控制,语言设置、主题颜色、字体大小、字体样

随机推荐

  1. 跟Google学习Android开发-起始篇-保存数
  2. 在eclipse中导入android4.0中的Launcher2
  3. android android 在list view中插入一条
  4. Android(安卓)贝塞尔曲线实现QQ拖拽清除
  5. android的gralloc分析
  6. android官方最新以及2.2、2.3.5源代码(完
  7. 利用WCF与Android实现图片上传并传参
  8. 如何在Android平台下编译带STL的C++程序
  9. Android闹钟拓展版【安卓闹钟可换壁纸版
  10. 百度 谷歌 地图WIFI定位原理