Created
July 23, 2012 14:13
-
-
Save tomasdev/3163830 to your computer and use it in GitHub Desktop.
Relative Time JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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