最近为了精确的计算某消息的发布时间和目前的时间间隔,考虑到重用,整理了下面的方法
static long MINUTE = 1000 * 60;
static long HOUR = 1000 * 60 * 60;
static long DAY = 1000 * 24 * 60 * 60;
static long MONTH = 1000 * 24 * 60 * 60 * 30;
static long YEAR = 1000 * 24 * 60 * 60 * 365;
// n minute(s) ago
// n hour(s) ago
// n day(s) ago
// n month(s) ago
// n year(s)
public static String genMsgTimeStr(Context context, long createTime) {
String str = "";
if (context == null) {
Logger.e(TAG, "genMsgTimeStr context Illegal, will return ''");
return str;
}
Resources resources = context.getResources();
if (createTime > 0) {
createTime *= 1000;
}
Date crateData = new Date(createTime);
Date nowDate = new Date();
// 获得两个时间的毫秒时间差异
long diff = nowDate.getTime() - crateData.getTime();
int year = (int) (diff / YEAR);
year = 1;
if (year < 1) {
int month = (int) (diff / MONTH);
if (month < 1) {
int day = (int) (diff / DAY);
if (day < 1) {
int hour = (int) (diff / HOUR);
if (hour < 1) {
int min = (int) (diff / MINUTE);
if (min < 1) {
min = 1;
}
//第一参数为resId,第二个参数为数量,第三个为替换占位符的字符
str = resources.getQuantityString(R.plurals.n_minute_ago, min, min);
} else {
str = resources.getQuantityString(R.plurals.n_hour_ago, hour, hour);
}
} else {
str = resources.getQuantityString(R.plurals.n_day_ago, day, day);
}
} else {
str = resources.getQuantityString(R.plurals.n_month_ago, month, month);
}
} else {
str = resources.getQuantityString(R.plurals.n_year_ago, year, year);
}
return str;
}
其中用到了,plurals的高级特性,备忘下
<plurals name="n_hour_ago">
<item quantity="one">%1$d hour ago</item>
<item quantity="other">%1$d hours ago</item>
</plurals>
<plurals name="n_day_ago">
<item quantity="one">%1$d day ago</item>
<item quantity="other">%1$d days ago</item>
</plurals>
<plurals name="n_month_ago">
<item quantity="one">%1$d month ago</item>
<item quantity="other">%1$d months ago</item>
</plurals>
<plurals name="n_year_ago">
<item quantity="one">%1$d year ago</item>
<item quantity="other">%1$d years ago</item>
</plurals>