Skip to content

Instantly share code, notes, and snippets.

@abdel
Last active September 26, 2015 10:38
Show Gist options
  • Save abdel/1084573 to your computer and use it in GitHub Desktop.
Save abdel/1084573 to your computer and use it in GitHub Desktop.
time_ago
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