Created
August 30, 2008 11:39
-
-
Save darragh/8105 to your computer and use it in GitHub Desktop.
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
/* | |
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 | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment