Skip to content

Instantly share code, notes, and snippets.

@tomasdev
Created July 23, 2012 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasdev/3163830 to your computer and use it in GitHub Desktop.
Save tomasdev/3163830 to your computer and use it in GitHub Desktop.
Relative Time JS
/**
* Relative time converter
* FIXME: fix hardcoded strings (ago, just now)
* @param {Date} dateObj Date object to convert to string
* @return {String}
*/
var relativeTime = function(dateObj) {
var delta = new Date() - dateObj;
now_threshold = 5000;
if (delta <= now_threshold) {
return 'just now';
}
var units = null, conversions = {
millisecond: 1,
second: 1000,
minute: 60,
hour: 60,
day: 24,
month: 30,
year: 12
};
for (var key in conversions) {
if (delta < conversions[key]) {
break;
} else {
units = key;
delta = delta / conversions[key];
}
}
delta = Math.floor(delta);
if (delta !== 1) { units += "s"; }
return [delta, units, " ago "].join(" ");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment