Skip to content

Instantly share code, notes, and snippets.

@leyafo
Last active August 9, 2017 18:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leyafo/c90fd840f4cdc9cdc156 to your computer and use it in GitHub Desktop.
Save leyafo/c90fd840f4cdc9cdc156 to your computer and use it in GitHub Desktop.
A simple ruby time ago convert
MINUTE = 60
HOUR = MINUTE*60
DAY = HOUR*24
WEEK = DAY*7
MONTH = DAY*30
YEAR = MONTH*12
def time_ago_in_words(near_time, far_time)
diff = near_time.to_i - far_time.to_i
str = ''
case diff
when 0..MINUTE
str = 'now'
when MINUTE..HOUR
str = "#{diff / MINUTE} minutes ago"
when HOUR..DAY
str = "#{diff / HOUR} hours ago"
when DAY..WEEK
str = "#{diff / DAY} days ago"
when WEEK..MONTH
str = "#{diff / WEEK} weeks ago"
when MONTH..YEAR
str = "#{diff / MONTH} month ago"
when YEAR..YEAR*20
str = "#{diff / YEAR} years ago"
else
str = "long long time ago"
end
str
end
now = Time.now
puts time_ago_in_words(now, Time.local(2000, "jan", 1, 20, 15, 1))
puts time_ago_in_words(now, Time.local(2014, "jan", 1, 20, 15, 1))
puts time_ago_in_words(now, Time.now)
puts time_ago_in_words(now, Time.local(now.year-1, "jan", 1, 20, 15, 1))
puts time_ago_in_words(now, Time.local(now.year, now.month-1, 1, 20, 15, 1))
puts time_ago_in_words(now, Time.local(now.year, now.month, now.day-1, now.hour, now.min , 1))
puts time_ago_in_words(now, Time.local(now.year, now.month, now.day, now.hour-1, 15, 1))
puts time_ago_in_words(now, Time.local(now.year, now.month, now.day, now.hour, now.min-1, 1))
puts time_ago_in_words(now, Time.local(now.year, now.month, now.day, now.hour, now.min, now.sec-10))
puts time_ago_in_words(now, Time.local(now.year-21, "jan", 1, 20, 15, 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment