从伊恩湖的回答:
final CharSequence relativeTimeSpan = DateUtils.getRelativeTimeSpanString(time, now, 0);
DateUtils.getRelativeTimeSpanString产生如下内容:
或者,这将允许res
使用给定的 Android 框架提供翻译Context
,如果您想要的消息传递与您可以从框架方法中得到的不同,这将很有用。
public static String getTimeAgo(long time, Context context) {
if (time < 1000000000000L)
// if timestamp given in seconds, convert to millis
time *= 1000;
final long now = getCurrentTime(context);
if (time > now || time <= 0) return "";
final Resources res = context.getResources();
final long time_difference = now - time;
if (time_difference < _A_MINUTE)
return res.getString(R.string.just_now);
else if (time_difference < 50 * _A_MINUTE)
return res.getString(R.string.time_ago,
res.getQuantityString(R.plurals.minutes, (int) time_difference / _A_MINUTE, time_difference / _A_MINUTE));
else if (time_difference < 24 * _AN_HOUR)
return res.getString(R.string.time_ago,
res.getQuantityString(R.plurals.hours, (int) time_difference / _AN_HOUR, time_difference / _AN_HOUR));
else if (time_difference < 48 * _AN_HOUR)
return res.getString(R.string.yesterday);
else
return res.getString(R.string.time_ago,
res.getQuantityString(R.plurals.days, (int) time_difference / _A_DAY, time_difference / _A_DAY));
}
我将常量定义为:
/** One second (in milliseconds) */
private static final int _A_SECOND = 1000;
/** One minute (in milliseconds) */
private static final int _A_MINUTE = 60 * _A_SECOND;
/** One hour (in milliseconds) */
private static final int _AN_HOUR = 60 * _A_MINUTE;
/** One day (in milliseconds) */
private static final int _A_DAY = 24 * _AN_HOUR;
然后剩下的工作就是复数和字符串资源的结构。
我的默认本地是 en,所以res/values/strings.xml
:
<!-- time ago strings -->
<string name="just_now">just now</string>
<string name="time_ago">%s ago</string>
<string name="yesterday">yesterday</string>
然后res/values/plurals.xml
:
<plurals name="minutes">
<item quantity="one">a minute</item>
<item quantity="other">%d minutes</item>
</plurals>
<plurals name="hours">
<item quantity="one">an hour</item>
<item quantity="other">%d hours</item>
</plurals>
<plurals name="days">
<item quantity="one">a day</item>
<item quantity="other">%d days</item>
</plurals>
这种方法应该允许您对语言的词汇和语法进行本地化,因为不同的语言不仅对“分钟”之类的词有不同的词,而且对于如何根据数量使词复数也有不同的规则。因此复数资源利用了 Android 框架对复数本地化的支持。剩下的就是提供翻译。