Skip to content

Instantly share code, notes, and snippets.

@scruffyfox
Forked from codeincontext/gist:1285806
Created November 2, 2011 15:23
Show Gist options
  • Save scruffyfox/1333916 to your computer and use it in GitHub Desktop.
Save scruffyfox/1333916 to your computer and use it in GitHub Desktop.
Javascript function to show how long ago a timestamp was as a pretty string
/**
* Converts a timestamp to how long ago syntax
* @param time The time in seconds
* @return The formatted time
*/
public static String timeAgo(int time)
{
Unit[] units = new Unit[]
{
new Unit("s", 60, 1),
new Unit("m", 3600, 60),
new Unit("h", 86400, 3600),
new Unit("d", 604800, 86400),
new Unit("w", 2629743, 604800),
new Unit("m", 31556926, 2629743),
new Unit("y", 0, 31556926)
};
long currentTime = System.currentTimeMillis();
int difference = (int)((currentTime / 1000) - (time));
if (currentTime < 5)
{
return "now";
}
int i = 0;
Unit unit = null;
while ((unit = units[i++]) != null)
{
if (difference < unit.limit || unit.limit == 0)
{
int newDiff = (int)Math.floor(difference / unit.inSeconds);
return newDiff + "" + unit.name;
}
}
return "";
}
static class Unit
{
public String name;
public int limit;
public int inSeconds;
public Unit(String name, int limit, int inSeconds)
{
this.name = name;
this.limit = limit;
this.inSeconds = inSeconds;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment