Skip to content

Instantly share code, notes, and snippets.

@dakaugu
Last active January 26, 2017 18:44
Show Gist options
  • Save dakaugu/80a3f8a2846b2de03789 to your computer and use it in GitHub Desktop.
Save dakaugu/80a3f8a2846b2de03789 to your computer and use it in GitHub Desktop.
Calculate time ago, for social media, forum applications. Ex: "Just now", "a minute ago", "2 weeks ago", "5 years ago", "Yesterday"
public static String calculateTimeAgo(long timeStamp) {
long timeDifference;
long unixTime = System.currentTimeMillis() / 1000L; //get current time in seconds.
int j;
String[] periods = {"s", "min", "hour", "day", "week", "month", "year", "decade"};
// full time intervals like seconds, minutes, days and so on
double[] lengths = {60, 60, 24, 7, 4.35, 12, 10};
timeDifference = unixTime - timeStamp;
String tense = "ago";
String plural = "s";
for (j = 0; timeDifference >= lengths[j] && j < lengths.length - 1; j++) {
timeDifference /= lengths[j];
}
if (timeDifference > 1 && j> 0){
return timeDifference + " " + periods[j] + plural + " " + tense;
}else if (timeDifference < 2 && j>=3){
if(j == 3) {
return "Yesterday";
}
return "a" + " " + periods[j] + " " + tense;
}else {
if(timeDifference <= 59 && periods[j].equals("s")){
return "just now";
}
return timeDifference + " " + periods[j] + " " + tense;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment