Created
December 13, 2011 09:24
-
-
Save nirix/1471370 to your computer and use it in GitHub Desktop.
time_ago
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
def time_ago(timestamp, from_timestamp = nil) | |
return if timestamp.nil? | |
from_timestamp = Time.now.to_i if from_timestamp.nil? | |
difference = from_timestamp - timestamp | |
periods = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'] | |
lengths = [60, 60, 24, 7, 4.35, 12, 10] | |
i = 0 | |
while difference >= lengths[i] | |
difference /= lengths[i] | |
i += 1 | |
end | |
difference = difference.ceil | |
periods[i] = periods[i] +'s' if difference != 1 | |
return "#{difference} #{periods[i]} ago" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment