Skip to content

Instantly share code, notes, and snippets.

@reinh
Created September 3, 2010 23:19
Show Gist options
  • Select an option

  • Save reinh/564706 to your computer and use it in GitHub Desktop.

Select an option

Save reinh/564706 to your computer and use it in GitHub Desktop.
def timesince(d, now=Time.now)
delta = (now - d).to_i
return "0 minutes" if delta <= 60
chunks = [
[60 * 60 * 24 * 356 , 'year' ],
[60 * 60 * 24 * 7 , 'week' ],
[60 * 60 * 24 , 'day' ],
[60 * 60 , 'hour' ],
[60 , 'minute' ]
]
pluralize = lambda {|amount, unit| "#{amount} #{unit}#{'s' if amount != 1}"}
ret = ""
chunks.each do |seconds, unit|
amount, delta = delta.divmod(seconds)
ret << pluralize[amount, unit] << ' ' if amount > 0
end
ret.strip
end
@reinh
Copy link
Copy Markdown
Author

reinh commented Sep 3, 2010

irb(main):001:0> timesince 1.day.ago
=> "1 day"
irb(main):002:0> timesince 23.hours.ago
=> "23 hours"
irb(main):003:0> timesince 3.minutes.ago
=> "3 minutes"
irb(main):004:0> timesince (1.year + 3.days + 5.hours + 3.minutes).ago
=> "1 year 1 week 5 days 5 hours 3 minutes"
irb(main):005:0> 

@reinh
Copy link
Copy Markdown
Author

reinh commented Sep 3, 2010

Month calculations are wrong ofc (not all months have 30 days)

@reinh
Copy link
Copy Markdown
Author

reinh commented Sep 3, 2010

Fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment