Last active
September 26, 2015 10:38
-
-
Save abdel/1084573 to your computer and use it in GitHub Desktop.
time_ago
This file contains hidden or 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) | |
if timestamp.nil? | |
return false | |
end | |
if from_timestamp.nil? | |
from_timestamp = Time.now.to_i | |
end | |
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 | |
if difference != 1 | |
periods[i] = periods[i]+'s' | |
end | |
return "#{difference} #{periods[i]} ago" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment