public
Last active

  • Download Gist
time_ago_in_words.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
/*
Use this small script to convert dates to a relative time in words.
uses prototype.. http://www.prototypejs.org/
inspired by rails distance_of_time_in_words helper http://apidock.com/rails/ActionView/Helpers/DateHelper/distance_of_time_in_words
 
http://blog.peelmeagrape.net/2008/8/30/time-ago-in-words-javascript-part-2
Fell free to use as you wish...
*/
TimeInWordsHelper = {
distanceInWords: function(fromTime, toTime, includeSeconds) {
var fromSeconds = fromTime.getTime();
var toSeconds = toTime.getTime();
var distanceInSeconds = Math.round(Math.abs(fromSeconds - toSeconds) / 1000)
var distanceInMinutes = Math.round(distanceInSeconds / 60)
if (distanceInMinutes <= 1) {
if (!includeSeconds)
return (distanceInMinutes == 0) ? 'less than a minute' : '1 minute'
if (distanceInSeconds < 5)
return 'less than 5 seconds'
if (distanceInSeconds < 10)
return 'less than 10 seconds'
if (distanceInSeconds < 20)
return 'less than 20 seconds'
if (distanceInSeconds < 40)
return 'half a minute'
if (distanceInSeconds < 60)
return 'less than a minute'
return '1 minute'
}
if (distanceInMinutes < 45)
return distanceInMinutes + ' minutes'
if (distanceInMinutes < 90)
return "about 1 hour"
if (distanceInMinutes < 1440)
return "about " + (Math.round(distanceInMinutes / 60)) + ' hours'
if (distanceInMinutes < 2880)
return "1 day"
if (distanceInMinutes < 43200)
return (Math.round(distanceInMinutes / 1440)) + ' days'
if (distanceInMinutes < 86400)
return "about 1 month"
if (distanceInMinutes < 525600)
return (Math.round(distanceInMinutes / 43200)) + ' months'
if (distanceInMinutes < 1051200)
return "about 1 year"
return "over " + (Math.round(distanceInMinutes / 525600)) + ' years'
},
convertBySelector: function(selector) {
var now = new Date()
$$(selector).each(function(e) {
var oldInner = e.innerHTML
e.innerHTML = TimeInWordsHelper.distanceInWords(now, new Date(e.title), false) + ' ago'
e.title = oldInner
});
}
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.