Android日期时间格式国际化的实现代码
在做多语言版本的时候,日期时间的格式话是一个很头疼的事情,幸好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