Skip to content

Instantly share code, notes, and snippets.

@Japh
Created December 20, 2011 06:54
Show Gist options
  • Select an option

  • Save Japh/1500589 to your computer and use it in GitHub Desktop.

Select an option

Save Japh/1500589 to your computer and use it in GitHub Desktop.
Javascript snippet for plain english relative time (e.g. "X seconds ago")
function time_ago(time) {
periods = new Array("second", "minute", "hour", "day", "week", "month", "year", "decade");
lengths = new Array("60","60","24","7","4.35","12","10");
nowdate = new Date();
now = (nowdate.getTime() / 1000);
difference = now - time;
tense = "ago";
for(j = 0; difference >= lengths[j] && j < lengths.length-1; j++) {
difference /= lengths[j];
}
difference = Math.round(difference);
if(difference != 1) {
periods[j] += "s";
}
return difference + ' ' + periods[j] + ' ago';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment