Skip to content

Instantly share code, notes, and snippets.

@dalethedeveloper
Created August 3, 2011 22:20
Show Gist options
  • Save dalethedeveloper/1123968 to your computer and use it in GitHub Desktop.
Save dalethedeveloper/1123968 to your computer and use it in GitHub Desktop.
Timestamp to a plain words description of elapsed delta (great for Twitter timestamps)
// Adapted from jQuery TimeAgo plugin:
// https://github.com/rmm5t/jquery-timeago/blob/master/jquery.timeago.js
// Update, check out performance: http://jsperf.com/twitter-relative-time-parsing
function timetowords(timestamp) {
var words = {
"seconds": "less than a minute",
"minute": "about a minute",
"minutes": "%d minutes",
"hour": "about an hour",
"hours": "about %d hours",
"day": "a day",
"days": "%d days",
"month": "about a month",
"months": "%d months",
"year": "about a year",
"years": "%d years"
},
deltaMilliseconds = (new Date().getTime() - timestamp),
seconds = deltaMilliseconds / 1000,
minutes = seconds / 60,
hours = minutes / 60,
days = hours / 24,
years = days / 365;
return seconds < 45 && words.seconds.replace(/%d/i,Math.round(seconds)) ||
seconds < 90 && words.minute.replace(/%d/i, 1) ||
minutes < 45 && words.minutes.replace(/%d/i, Math.round(minutes)) ||
minutes < 90 && words.hour.replace(/%d/i, 1) ||
hours < 24 && words.hours.replace(/%d/i, Math.round(hours)) ||
hours < 48 && words.day.replace(/%d/i, 1) ||
days < 30 && words.days.replace(/%d/i, Math.floor(days)) ||
days < 60 && words.month.replace(/%d/i, 1) ||
days < 365 && words.months.replace(/%d/i, Math.floor(days / 30)) ||
years < 2 && words.year.replace(/%d/i, 1) ||
words.years.replace(/%d/i, Math.floor(years));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment