Human Time
- Posted: 11 months ago
- Tags:code, ruby, site
- 0 comments
I recently added the capability to display time in more human friendly terms. Basically, instead of saying Posted at 2007-11-30 20:18:36, a relevant post will say "posted 3 days ago". You can see this on every post or twitter on my site. I did not realize the full potential of Ruby until I sat down to write the code to make this happen. I simply extended Ruby's default Time class with the following:
class Time
def humantime
age = Time.now.to_i - self.to_i
seconds_max = 60
minutes_max = 3600
hours_max = 86400
days_max = 604800
weeks_max = 2629743
months_max = 31556926
p = ''
unit = ' second'
if age < seconds_max
amt = age
elsif age < minutes_max
amt = age/seconds_max
unit = ' minute'
elsif age < hours_max
amt = age/minutes_max
unit = ' hour'
elsif age < days_max
amt = age/hours_max
unit = ' day'
elsif age < weeks_max
amt = age/days_max
unit = ' week'
elsif age < months_max
amt = age/weeks_max
unit = ' month'
else
amt = age/months_max
unit = ' year'
end
if amt > 1
p = 's'
end
humantime = amt.to_s + unit + p + " ago"
end
end
So now, to get the time in human time, I just call the .humantime method that is now a part of every Time object.
