package com.sample;
import java.util.Date;
public class TimeAgo {
public final static long ONE_SECOND = 1000;
public final static long ONE_MINUTE = ONE_SECOND * 60;
public final static long ONE_HOUR = ONE_MINUTE * 60;
public final static long ONE_DAY = ONE_HOUR * 24;
public final static long ONE_WEEK = ONE_DAY * 7;
public final static long ONE_MONTH = ONE_DAY * 30;
public final static long ONE_YEAR = ONE_MONTH * 12;
public static String getTimeAgo(long time) {
StringBuffer res = new StringBuffer();
long temp = 0;
if (time >= ONE_SECOND) {
temp = time / ONE_YEAR;
if (temp > 0) {
time -= temp * ONE_YEAR;
return res.append(temp).append(" year").append(temp > 1 ? "s" : "")
.append(time >= ONE_YEAR ? ", " : " ago").toString();
}
temp = time / ONE_MONTH;
if (temp > 0) {
time -= temp * ONE_MONTH;
return res.append(temp).append(" month").append(temp > 1 ? "s" : "")
.append(time >= ONE_MONTH ? ", " : " ago").toString();
}
temp = time / ONE_WEEK;
if (temp > 0) {
time -= temp * ONE_WEEK;
return res.append(temp).append(" week").append(temp > 1 ? "s" : "")
.append(time >= ONE_WEEK ? ", " : " ago").toString();
}
temp = time / ONE_DAY;
if (temp > 0) {
time -= temp * ONE_DAY;
return res.append(temp).append(" day").append(temp > 1 ? "s" : "")
.append(time >= ONE_MINUTE ? ", " : " ago").toString();
}
temp = time / ONE_HOUR;
if (temp > 0) {
time -= temp * ONE_HOUR;
return res.append(temp).append(" hour").append(temp > 1 ? "s" : "")
.append(time >= ONE_MINUTE ? ", " : " ago").toString();
}
temp = time / ONE_MINUTE;
if (temp > 0) {
time -= temp * ONE_MINUTE;
return res.append(temp).append(" minute").append(temp > 1 ? "s" : " ago").toString();
}
if (!res.toString().equals("") && time >= ONE_SECOND) {
return res.append(" and ").toString();
}
temp = time / ONE_SECOND;
if (temp > 0) {
return res.append(temp).append(" second").append(temp > 1 ? "s" : " ago").toString();
}
return res.toString();
} else {
return "0 second ago";
}
}
public static String getTimeAgo(Date lastLogin) {
return getTimeAgo(lastLogin.getTime());
}
public static void main(String args[]) {
System.out.println(getTimeAgo(123));
System.out.println(getTimeAgo(1230));
System.out.println(getTimeAgo(12300));
System.out.println(getTimeAgo(123000));
System.out.println(getTimeAgo(1230000));
System.out.println(getTimeAgo(12300000));
System.out.println(getTimeAgo(123000000));
System.out.println(getTimeAgo(1230000000));
System.out.println(getTimeAgo(12300000000L));
System.out.println(getTimeAgo(123000000000L));
}
}
Output:
0 second ago
1 second ago
12 seconds
2 minutes
20 minutes
3 hours,
1 day,
2 weeks ago
4 months ago
3 years ago