Skip to content

Instantly share code, notes, and snippets.

@nirix
Created December 13, 2011 09:24
Show Gist options
  • Save nirix/1471370 to your computer and use it in GitHub Desktop.
Save nirix/1471370 to your computer and use it in GitHub Desktop.
time_ago
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