Skip to content

Instantly share code, notes, and snippets.

@yava555
Created March 15, 2016 03:09
Show Gist options
  • Save yava555/5c853705b8d38eaa3c3b to your computer and use it in GitHub Desktop.
Save yava555/5c853705b8d38eaa3c3b to your computer and use it in GitHub Desktop.
times ago
private static final long SECOND_MILLIS = 1000;
private static final long MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final long HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final long DAY_MILLIS = 24 * HOUR_MILLIS;
private static final long MONTH_MILLIS = 30 * DAY_MILLIS;
private static final long YEAR_MILLIS = 12 * MONTH_MILLIS;
public static String getTimeAgo(long time) {
if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = System.currentTimeMillis();
if (time > now || time <= 0) {
return "刚刚";
}
final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "刚刚";
} else if (diff < HOUR_MILLIS) {
return diff / MINUTE_MILLIS + "分钟前";
} else if (diff < DAY_MILLIS) {
return diff / HOUR_MILLIS + "小时前";
} else if (diff < MONTH_MILLIS) {
return diff / DAY_MILLIS + "天前";
} else if (diff < YEAR_MILLIS) {
return diff / MONTH_MILLIS + "月前";
} else {
return diff / YEAR_MILLIS + "年前";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment